1、通过@controllerAdvice 注解,我们可以在一个地方对所有@controller注解的控制器进行管理
注解了@ControllerAdvice 的类的方法可以使用 @ExceptionHandler、@InitBinder、@ModelAttribute 注解到方法上,这对所有注解了@RequestMapping的控制器内的方法都有效
2、@ExceptionHandler:用于捕获所有控制器里面的异常,并进行处理
3、InitBinder: 用来设置 webDataBinder, webDataBinder 用来自动绑定前台请求参数到Model中
4、@ModelAttribute: @ModelAttribute 本来的作用是绑定键值对到Model里,此处是让全局的@RequestMapping都能获得在此处设置的键值对。
本文使用@ControllerAdvice + @ExceptionHandler 进行全局的Controller层的异常处理。
统一异常返回结果类
public class ExceptionResult implements Serializable {
private Integer code;
private String message;
public ExceptionResult() {
}
public ExceptionResult(Integer code, String message) {
this.code = code;
this.message = message;
}
public static ExceptionResult fail(Integer code, String message) {
return new ExceptionResult(code, message);
}
public static ExceptionResult fail(String message) {
return fail(500, message);
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
自定义业务异常类 BaseException
public class BaseException extends RuntimeException implements Serializable {
/**
* 错误码
*/
private Integer code;
public BaseException() {
}
public BaseException(String s) { this(500,s);}
public BaseException(Integer code, String s) {
super(s);
this.code = code;
}
public BaseException(String s, Throwable throwable) {super(s,throwable);}
public BaseException(Throwable throwable) {super(throwable);}
public BaseException(String s, Throwable throwable, boolean b, boolean b1) {super(s,throwable,b,b1);}
public Integer getCode() {return code;}
}
全局异常处理类 GlobalExceptionHandler
@ControllerAdvice
public class GlobalExceptionHandler {
//该注解用于捕获所有控制器里面的异常,并进行处理
@ExceptionHandler(Exception.class)
public ResponseEntity<ExceptionResult> failed(Exception e){
String msg = "服务器出现未知异常";
ExceptionResult exceptionResult = ExceptionResult.fail(500, "服务器出现未知异常");
//业务异常
if (e instanceof BaseException) {
exceptionResult.setCode(((BaseException) e).getCode());
msg = e.getMessage();
}
//不合法、不正确的参数
if (e instanceof IllegalArgumentException) {
msg = e.getMessage();
}
//接口异常 前端页面传过来的参数与你controller接收的参数类型不匹配
if (e instanceof HttpMessageNotReadableException) {
msg = "请求参数不合规,请校验后重新提交";
}
//参数校验异常
if (e instanceof MethodArgumentNotValidException) {
msg = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
}
if (e instanceof HttpRequestMethodNotSupportedException) {
msg = "不支持的请求方式";
}
String exceptionClassName = e.getClass().getName();
exceptionClassName =exceptionClassName.substring(exceptionClassName.lastIndexOf('.') + 1);
exceptionResult.setMessage(msg);
return new ResponseEntity<>(exceptionResult, HttpStatus.OK);
}
}