controller全局异常统一处理
代码示例:
/**
* 全局异常
**/
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 缺失参数异常处理器
*
* @param e 缺失参数异常
* @return ResponseResult
*/
@ExceptionHandler(MissingServletRequestParameterException.class)
public ApiResult parameterMissingExceptionHandler(MissingServletRequestParameterException e) {
return ApiResult.error(CodeMsg.SERVER_ERROR.getCode(), "请求参数 " + e.getParameterName() + " 不能为空");
}
/**
* 缺少请求体异常处理器
*
* @param e 缺少请求体异常
* @return ResponseResult
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public ApiResult parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
return ApiResult.error(CodeMsg.SERVER_ERROR.getCode(), "参数体不能为空");
}
/**
* 自定义异常
**/
@ExceptionHandler(value = BizException.class)
public ApiResult handle(BizException e) {
return ApiResult.error(e.getCode(), e.getMsg());
}
/**
* 全局异常
**/
@ExceptionHandler(Exception.class)
public ApiResult exceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
String message = exception.getMessage() + request.getRequestURL().toString();
return ApiResult.error(CodeMsg.SERVER_ERROR.getCode(), message);
}
/**
* 校验异常
**/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ApiResult handleValidException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
StringBuilder message = new StringBuilder();
if (bindingResult.hasErrors()) {
FieldError fieldError = bindingResult.getFieldError();
if (fieldError != null) {
message.append(fieldError.getDefaultMessage()).append("!");
}
}
return ApiResult.error(CodeMsg.BIND_ERROR.getCode(), message.toString());
}
/**
* 如果是controller方法中单个参数的校验, 则需要捕获该异常
* 如方法参数:@Length(max = 4) @RequestParam("username") String username
* 需要在controller类上添加@Validated,否则不生效
**/
@ExceptionHandler(value = ConstraintViolationException.class)
public ApiResult handleConstraintViolationException(ConstraintViolationException e) {
StringBuilder message = new StringBuilder();
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
constraintViolations.stream().forEach(item -> {
message.append(item.getMessage()).append("!");
});
return ApiResult.error(CodeMsg.BIND_ERROR.getCode(), message.toString());
}
}
以上涉及到的CodeMsg、ApiResult、BizException,可以参考:分页对象、状态码、返回结果对象、自定义异常