Spring中通过java的@Valid注解和@ControllerAdvice实现全局异常处理。
Posted tangquanbin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring中通过java的@Valid注解和@ControllerAdvice实现全局异常处理。相关的知识,希望对你有一定的参考价值。
通过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等是自己封装的处理工具类。
以上是关于Spring中通过java的@Valid注解和@ControllerAdvice实现全局异常处理。的主要内容,如果未能解决你的问题,请参考以下文章