统一异常拦截类
@ControllerAdvice
public class GlobalExceptionHandler {
public static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = ServiceException.class)
@ResponseBody
public ResponseResult<String> serviceExceptionHandler(ServiceException e) {
logger.warn("发生业务错误,原因:{}", e.getMessage());
return ResponseResult.customResult(e.getExceptionEnum());
}
@ExceptionHandler(value = UnauthorizedException.class)
@ResponseBody
public ResponseResult<String> unauthorizedExceptionHandler(UnauthorizedException e) {
logger.warn("接口请求权限错误:{}", e.getMessage());
return ResponseResult.customResult(CommonExceptionEnum.NO_PERMISSION);
}
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseResult<String> exceptionHandler(Exception e) {
e.printStackTrace();
logger.warn("未知错误,原因:{}", e.getMessage());
return ResponseResult.customResult(CommonExceptionEnum.DEFAULT_ERROR);
}
/**
* 参数异常统一处理
*/
@Order(1)
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseResult<Object> validationException(MethodArgumentNotValidException exception) {
BindingResult bindingResult = exception.getBindingResult();
FieldError fieldError;
if (bindingResult.hasErrors() && (fieldError = bindingResult.getFieldError()) != null) {
return ResponseResult.customResult(CommonExceptionEnum.PARAM_ERROR, fieldError.getDefaultMessage());
} else {
return ResponseResult.customResult(CommonExceptionEnum.DEFAULT_ERROR);
}
}
}
统一请求参数校验类
/**
* 参数异常统一处理
*/
@Order(1)
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseResult<Object> validationException(MethodArgumentNotValidException exception) {
BindingResult bindingResult = exception.getBindingResult();
FieldError fieldError;
if (bindingResult.hasErrors() && (fieldError = bindingResult.getFieldError()) != null) {
return ResponseResult.customResult(CommonExceptionEnum.PARAM_ERROR, fieldError.getDefaultMessage());
} else {
return ResponseResult.customResult(CommonExceptionEnum.DEFAULT_ERROR);
}
}
@PostMapping(value = "/123")
public ResponseResult<String> saveOrg(@RequestBody @Valid SaveOrgDto sysZcjg) {
return sysZcjgService.saveOrg(sysZcjg);
}
public class SaveOrgDto {
@NotBlank(message = "xxx不能为空")
private String jgbm;
}
https://zhuanlan.zhihu.com/p/158774914