springboot全局异常处理类
2019-09-30 本文已影响0人
writeanewworld
1.注解
主要是用了个 @RestControllerAdvice 注解。拦截controller层的异常统一处理
- 代码
写个GlobalExceptionHandler:
@RestControllerAdvice
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Throwable.class)
public BaseResponse handler(HttpServletRequest request, Throwable e) {
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
String errMsg = ex.getBindingResult().getFieldError().getDefaultMessage();
return ResponseTools.newErrorResponse(101, errMsg);
} else if (e instanceof NoHandlerFoundException) {
return ResponseTools.newErrorResponse(404, "请求资源不存在!");
} else if (e instanceof BindException) {
BindException ex = (BindException) e;
String errMsg = ex.getBindingResult().getFieldError().getDefaultMessage();
return ResponseTools.newErrorResponse(102, errMsg);
} else if (e instanceof ServletRequestBindingException) {
ServletRequestBindingException ex = (ServletRequestBindingException) e;
return ResponseTools.newErrorResponse(105, ex.getMessage());
} else if (e instanceof HttpRequestMethodNotSupportedException) {
HttpRequestMethodNotSupportedException ex = (HttpRequestMethodNotSupportedException) e;
return ResponseTools.newErrorResponse(405, "请求方法不支持" + ex.getMethod());
} else if (e instanceof Exception) {
logger.error("未知异常 {}", e.getMessage(), e);
return ResponseTools.newErrorResponse(ReturnCode.UNKNOW_REEOR);
}
return ResponseTools.newErrorResponse(ReturnCode.UNKNOW_REEOR);
}
}