1.编写自定义异常类
继承RuntimeException
public class LoginException extends RuntimeException{
public LoginException(String message) {
super(message);
}
}
注:spring 对于 RuntimeException 异常才会进行事务回滚
2.编写全局异常处理类
@RestControllerAdvice
public class ExceptionController{
// 当捕获的异常 是 LogicException异常的时候
@ExceptionHandler(LoginException.class)
public Object LxExp(Exception e, HttpServletResponse response){
response.setContentType("application/json;charset=utf-8");
return JsonResult.error(JsonResult.CODE_ERROR,e.getMessage(),null);
}
// 当捕获运行运行时异常
@ExceptionHandler(RuntimeException.class)
public Object runtimeExp(Exception e, HttpServletResponse response){
response.setContentType("application/json;charset=utf-8");
return JsonResult.error(JsonResult.CODE_ERROR,JsonResult.MSG_ERROR,null);
}
}
-
@ExceptionHandler 配置的 value 指定需要拦截的异常类型,上面拦截了 Exception.class 这种异常
-
@RestControllerAdvice都是对Controller进行增强的,可以全局捕获spring mvc抛的异常