Spring的@ExceptionHandler和@ControllerAdvice统一处理异常

之前敲代码的时候,避免不了各种try..catch, 如果业务复杂一点, 就会发现全都是try…catch

try{
..........
}catch(Exception1 e){
..........
}catch(Exception2 e){
...........
}catch(Exception3 e){
...........
}

这样其实代码既不简洁好看 ,我们敲着也烦, 一般我们可能想到用拦截器去处理, 但是既然现在Spring这么火,AOP大家也不陌生, 那么Spring一定为我们想好了这个解决办法.果然: @ExceptionHandler

源码

//该注解作用对象为方法
@Target({ElementType.METHOD})
//在运行时有效
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
//value()可以指定异常类
Class<? extends Throwable>[] value() default {};
}

 @ControllerAdvice
源码

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
//bean对象交给spring管理生成
@Component
public @interface ControllerAdvice {
@AliasFor("basePackages")
String[] value() default {};

@AliasFor("value")
String[] basePackages() default {};

Class<?>[] basePackageClasses() default {};

Class<?>[] assignableTypes() default {};

Class<? extends Annotation>[] annotations() default {};
}

从名字上可以看出大体意思是控制器增强

所以结合上面我们可以知道,使用@ExceptionHandler,可以处理异常, 但是仅限于当前Controller中处理异常, @ControllerAdvice可以配置basePackage下的所有controller. 所以结合两者使用,就可以处理全局的异常了.

 1.定义一个异常
public class CustomGenericException extends RuntimeException{
private static final long serialVersionUID = 1L;

private String errCode;
private String errMsg;

public String getErrCode() {
return errCode;
}

public void setErrCode(String errCode) {
this.errCode = errCode;
}

public String getErrMsg() {
return errMsg;
}

public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}

public CustomGenericException(String errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
}

2. 定义一个controller
这里我们就不用try catch了, 直接抛异常就可以了

@Controller
@RequestMapping("/exception")
public class ExceptionController {

@RequestMapping(value = "/{type}", method = RequestMethod.GET)
public ModelAndView getPages(@PathVariable(value = "type") String type) throws Exception{
if ("error".equals(type)) {
// 由handleCustomException处理
throw new CustomGenericException("E888", "This is custom message");
} else if ("io-error".equals(type)) {
// 由handleAllException处理
throw new IOException();
} else {
return new ModelAndView("index").addObject("msg", type);
}
}
}

3.异常处理类
这个类就可以当做controller类写了, 返回参数跟mvc返回参数一样

@ControllerAdvice
public class ExceptionsHandler {

@ExceptionHandler(CustomGenericException.class)//可以直接写@ExceptionHandler,不指明异常类,会自动映射
public ModelAndView customGenericExceptionHnadler(CustomGenericException exception){ //还可以声明接收其他任意参数
ModelAndView modelAndView = new ModelAndView("generic_error");
modelAndView.addObject("errCode",exception.getErrCode());
modelAndView.addObject("errMsg",exception.getErrMsg());
return modelAndView;
}

//可以通过ResponseStatus配置返回的状态码
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)//可以直接写@EceptionHandler,IOExeption继承于Exception
public ModelAndView allExceptionHandler(Exception exception){
ModelAndView modelAndView = new ModelAndView("generic_error");
modelAndView.addObject("errMsg", "this is Exception.class");
return modelAndView;
}
}

4.jsp页面
正常的页面

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h2>Spring MVC @ExceptionHandler Example</h2>

<c:if test="${not empty msg}">
<h2>${msg}</h2>
</c:if>

</body>
</html>

异常处理页面

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>

<c:if test="${not empty errCode}">
<h1>${errCode} : System Errors</h1>
</c:if>

<c:if test="${empty errCode}">
<h1>System Errors</h1>
</c:if>

<c:if test="${not empty errMsg}">
<h2>${errMsg}</h2>
</c:if>

</body>
</html>

猜你喜欢

转载自www.cnblogs.com/jxldjsn/p/10825098.html