- /**
- * @author w
- * @desc 自定义异常类 捕获自动映射实体类参数校验异常
- */
- @ControllerAdvice
- @ResponseBody
- public class MyExceptionHandle {
- private static Logger logger = LoggerFactory.getLogger(MyExceptionHandle.class);
-
- @ExceptionHandler(MethodArgumentNotValidException.class)
- public BaseResponse handleBindException(MethodArgumentNotValidException ex) {
- FieldError fieldError = ex.getBindingResult().getFieldError();
- logger.error("MethodArgumentNotValidException {}:{}({})", ResultEnum.RESPONSE_MSG_PARAM_INVALID.getMessage(), fieldError.getDefaultMessage(),fieldError.getField());
- BaseResponse response = new BaseResponse();
- response.setCode(ResultEnum.RESPONSE_MSG_PARAM_INVALID.getCode());
- response.setMessage(ResultEnum.RESPONSE_MSG_PARAM_INVALID.getMessage() + fieldError.getDefaultMessage());
- logger.info(JSON.toJSONString(response));
- return response;
- }
-
-
- @ExceptionHandler(BindException.class)
- public BaseResponse handleBindException(BindException ex) {
- //校验 除了 requestbody 注解方式的参数校验 对应的 bindingresult 为 BeanPropertyBindingResult
- FieldError fieldError = ex.getBindingResult().getFieldError();
- logger.error("BindException {}:{}({})", ResultEnum.RESPONSE_MSG_PARAM_INVALID.getMessage(), fieldError.getDefaultMessage(), fieldError.getField());
- String errMsg = fieldError.getDefaultMessage();
- if(StringUtils.isBlank(errMsg)) {
- errMsg = fieldError.getField() + "不能为空";
- }
- BaseResponse response = new BaseResponse();
- response.setCode(ResultEnum.RESPONSE_MSG_PARAM_INVALID.getCode());
- response.setMessage(ResultEnum.RESPONSE_MSG_PARAM_INVALID.getMessage() + errMsg);
- logger.info(JSON.toJSONString(response));
- return response;
- }
-
- @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
- public BaseResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
- //拦截http请求方法不允许 ,如:post方法使用get方式
- String error = ex.getMessage();
- logger.error("HttpRequestMethodNotSupportedException \n{}\n请求方式:{}\n允许方式:{}", error, ex.getMethod(), ex.getSupportedMethods());
- BaseResponse response = new BaseResponse();
- response.setCode(ResultEnum.RESPONSE_MSG_METHOD_NOT_SUPPORT.getCode());
- response.setMessage(ResultEnum.RESPONSE_MSG_METHOD_NOT_SUPPORT.getMessage() + error + " by " + ex.getSupportedMethods()[0]);
- logger.info(JSON.toJSONString(response));
- return response;
- }
-
- @ExceptionHandler(RuntimeException.class)
- public BaseResponse handleException(RuntimeException ex) {
- ex.printStackTrace();
- //拦截异常
- logger.error("RuntimeException \n{}\n{}\n{}\n{}", ex.getLocalizedMessage(), ex.getCause(), ex.getStackTrace(), ex.getMessage());
- BaseResponse response = new BaseResponse();
- response.setCode(ResultEnum.RESPONSE_MSG_ERROR.getCode());
- response.setMessage(ResultEnum.RESPONSE_MSG_ERROR.getMessage() + ex.getMessage());
-
- logger.info(JSON.toJSONString(response));
- return response;
- }
- }
效果