一、介绍
在解决controller层抛出的异常时,为了使我们的代码更容易维护,创建一个类集中处理异常,通过实现 @ControllerAdvice注解捕获,配合 @ExceptionHandler来增强所有的@RequestMapping方法。
@ExceptionHandler:统一处理某一类异常,从而能够减少代码重复率和复杂度
该注解作用对象为方法,并且在运行时有效,value()可以指定异常类。异常参数:包括一般的异常或特定的异常(即自定义异常),如果注解没有指定异常类,会默认进行映射。
@ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开
二、具体实现
例如:@ExceptionHandler(Exception.class) 用来捕获@requestMapping的方法中所有抛出的exception。
/** * 统一异常处理类 */
@ControllerAdvice
public class BaseExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result error( Exception e) {
e.printStackTrace();
return new Result(false,StatusCode.ERROR, e.getMessage()); } }
有的时候,我们需要业务逻辑时抛出自定义异常,这个时候需要自定义业务异常类
1、定义类,返回异常结果信息
public class Result {
private Integer code;
private String msg;
public Result(Integer code,String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
2.定义一个业务异常类
说明:因为某些业务需要进行业务回滚。但spring的事务只针对RuntimeException的进行回滚操作。所以需要回滚就要继承RuntimeException。
public class BusinessException extends RuntimeException{
private static final long serialVersionUID = 1L;
private Integer code; //错误码
public BusinessException() {}
public BusinessException(Result result) {
super(result.getMsg());
this.code = result.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
3.定义一个全局异常处理类
@ControllerAdvice
public class GlobalDefultExceptionHandler {
// 捕捉UnauthorizedException
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(UnauthorizedException.class)
public ModelAndView handleUnauthorizedException(HttpServletResponse resp,HttpServletRequest req,UnauthorizedException e) {
logger.error(e.getMessage(),e);
return ResultUtil.error(ResultEnum.CODE_403,errors.toString());
}
//声明要捕获的异常(自定义异常和Exception)
@ExceptionHandler(Exception.class)
@ResponseBody
public <T> Result<?> defultExcepitonHandler(HttpServletRequest request,Exception e) {
e.printStackTrace();
if(e instanceof BusinessException) {
Log.error(this.getClass(),"业务异常:"+e.getMessage());
BusinessException businessException = (BusinessException)e;
return ResultUtil.error(businessException.getCode(), businessException.getMessage());
}
//未知错误
return ResultUtil.error(-1, "系统异常:\\n"+e);
}
}