SpringMVC 学习笔记(十) 异常处理HandlerExceptionResolver

Spring MVC 通过 HandlerExceptionResolver 处理程序的异常,包括 Handler 映射、数据绑定以及目标方法执行时发生的异常。

SpringMVC 提供的 HandlerExceptionResolver 的实现类


DispatcherServlet 默认装配的 HandlerExceptionResolver 


如果添加了<mvc:annotation-driven/> 则装配变为:




1.1. ExceptionHandlerExceptionResolver

ExceptionHandlerExceptionResolver 主要处理 Handler 中用 @ExceptionHandler 注解定义的方法。

@ExceptionHandler 注解定义的方法优先级问题:例如发生的是NullPointerException,但是声明的异常有RuntimeException 和 Exception,此候会根据异常的最近继承关系找到继承深度最浅的那个 @ExceptionHandler注解方法,即标记了 RuntimeException 的方法

ExceptionHandlerMethodResolver 内部若找不到 @ExceptionHandler 注解的话,会找 @ControllerAdvice 中的 @ExceptionHandler 注解方法

Java:

package com.ibigsea.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ExceptionController {
	
	/**
	 * 如果执行此Controller里面的方法出现<b>数学异常</b>,则会执行该方法
	 * @param e
	 * @return
	 */
	@ExceptionHandler({ArithmeticException.class})
	public String arithmeticException(Exception e){
		System.out.println("arithmeticException:"+e);
		return "error";
	}
	
	/**
	 * 如果执行此Controller里面的方法出现异常,则会执行该方法
	 * @param e
	 * @return
	 */
	@ExceptionHandler({Exception.class})
	public String exceptionHandle(Exception e){
		System.out.println("Exception"+e);
		return "error";
	}
	
	@RequestMapping("/exception")
	public String exception(Integer i){
		System.out.println(10/i);
		return "success";
	}   
	
}

上述异常处理代码会优先执行arithmeticException方法.

或者在类上面添加@ControllerAdvice注解

package com.ibigsea.springmvc.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class TestExceptionHandler {
	
	@ExceptionHandler({ArithmeticException.class})
	public String handleException(Exception e) {
		System.out.println("----> 出异常了: " + e);
		return "error";
	}
	
}


注意:


因为在执行@ExceptionHandler修饰的方法时没有传入BindingAwareModelMap对象,所以不能在方法上面添加额外的形参

1.2. ResponseStatusExceptionResolver 

l 在异常及异常父类中找到 @ResponseStatus 注解,然后使用这个注解的属性进行处理。

l 定义一个 @ResponseStatus 注解修饰的异常类

l 若在处理器方法中抛出了上述异常:若ExceptionHandlerExceptionResolver 不解析该异常。由于触发的异常 UnauthorizedException 带有@ResponseStatus注解。因此会被ResponseStatusExceptionResolver 解析到。最后响应HttpStatus.UNAUTHORIZED 代码给客户端。HttpStatus.UNAUTHORIZED 代表响应码401,无权限。关于其他的响应码请参考 HttpStatus 枚举类型源码。

Java:

	@RequestMapping("/responseStatus")
	public String responseStatus(Integer i){
		
		if (i>20) {
			throw new TestResponseStatusException();
		}
		
		return "success";
	}

package com.ibigsea.springmvc.exceptionresolver;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value=HttpStatus.FORBIDDEN, reason="测试@ResponseStatus!")
public class TestResponseStatusException extends RuntimeException {

	private static final long serialVersionUID = 4566548902417978204L;
	
}

结果:



1.3. DefaultHandlerExceptionResolver 

对一些特殊的异常进行处理,比如NoSuchRequestHandlingMethodExceptionHttpRequestMethodNotSupportedExceptionHttpMediaTypeNotSupportedExceptionHttpMediaTypeNotAcceptableException等。


	@RequestMapping(value="/defaultHandler",method=RequestMethod.POST)
	public String defaultHandlerException(){
		return "success";
	}

1.4. SimpleMappingExceptionResolver

如果希望对所有异常进行统一处理,可以使用SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常

 

JAVA

	@RequestMapping("/simpleMapping")
	public String simpleMappingException(Integer i){
		String[] strs = new String[10];
		System.out.println(strs[i]);
		return "success";
	}

Spring-mvc.xml

	<!-- 配置使用SimpleMappingExceptionResolver来映射异常 -->
	<bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionAttribute" value="ex"></property>
		<property name="exceptionMappings">
			<props>
				<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
			</props>
		</property>
	</bean>







  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring MVC中,可以通过以下几种方式来处理异常: 1. 使用@ControllerAdvice注解和@ExceptionHandler注解: - 首先,创建一个全局的异常处理类,使用@ControllerAdvice注解标注,并在类中定义一个或多个带有@ExceptionHandler注解的方法,用于处理特定的异常类型。 - 在异常处理方法中,可以定义需要执行的逻辑,例如记录日志、返回自定义错误信息等。 - 这种方式可以捕获并处理控制器中抛出的异常,提供统一的异常处理机制。 2. 使用@ExceptionHandler注解: - 在控制器类中,可以使用@ExceptionHandler注解标注方法,用于处理特定的异常类型。 - 这种方式适合处理控制器中的异常,可以针对不同的异常类型定义不同的处理逻辑。 3. 使用HandlerExceptionResolver接口: - 可以实现HandlerExceptionResolver接口,并注册为Spring的bean。 - 通过实现该接口的resolveException方法,可以自定义异常处理逻辑。 - 这种方式可以自定义异常处理的策略,例如根据异常类型、请求路径等进行不同的处理。 4. 使用@ControllerAdvice注解和@ModelAttribute注解: - 在全局异常处理类中,可以使用@ModelAttribute注解定义一个方法,用于在异常处理方法执行前,向模型中添加一些通用的属性。 - 这种方式适合在异常处理前,向模型中添加一些额外的信息,以便在异常处理方法中使用。 以上是几种常见的Spring MVC异常处理方式,根据具体的需求和场景,选择适合的方式进行异常处理

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值