通过java原生的@Valid注解和spring的@ControllerAdvice和@ExceptionHandler实现全局异常处理的方法:
controller中加入@Valid注解:
@RequestMapping(value="/addCountry", method=RequestMethod.POST) public ResponseResult addCountry(@RequestBody @Valid Country country) { return null; }
接受entity中加入@NotNull注解:(验证还有很多,这里是举例说明)
@NotNull(message = "countryname params must not be null.") private String countryname;
全局处理工具类加入@ControllerAdvice和@ExceptionHandler注解:
@ControllerAdvice public class GlobalExceptionAdvisor { Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvisor.class); /** * 提取Validator产生的异常错误 * @param bindingResult * @return */ private BaseException parseBindingResult(BindingResult bindingResult){ Map<String,String> errorMsgs = new HashMap<String,String>(); for (FieldError error:bindingResult.getFieldErrors()){ errorMsgs.put(error.getField(),error.getDefaultMessage()); } if(errorMsgs.isEmpty()) { return new IllegalParameterCommonException(); }else { return new IllegalParameterCommonException(JsonUtils.toJSONString(errorMsgs)); } } /** * 捕获@Validate校验抛出的异常 * @param e * @param request * @param response * @return */ @ExceptionHandler(BindException.class) @ResponseBody public ResponseResult validExceptionHandler(BindException e, HttpServletRequest request, HttpServletResponse response) { BaseException ex = parseBindingResult(e.getBindingResult()); logger.error(ex.getMessage()); return ResultUtil.error(ex); } /** * 捕获@Validate校验抛出的异常 * @param e * @param request * @param response * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public ResponseResult validException2Handler(MethodArgumentNotValidException e, HttpServletRequest request, HttpServletResponse response) { BaseException ex = parseBindingResult(e.getBindingResult()); logger.error(ex.getMessage()); return ResultUtil.error(ex); } @ExceptionHandler(value = BaseException.class) @ResponseBody public ResponseResult gisExceptionHandler(HttpServletRequest req, BaseException e) throws Exception { logger.error(e.getMessage()); return ResultUtil.error(e); } @ExceptionHandler(value = Exception.class) @ResponseBody public ResponseResult exceptionHandler(HttpServletRequest req, Exception e) throws Exception { logger.error(e.toString()); return ResultUtil.error(new BaseException()); } }
BaseException、ResponseResult等是自己封装的处理工具类。
原文地址:https://www.cnblogs.com/tangquanbin/p/10312001.html
时间: 2024-10-06 10:11:28