• 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等是自己封装的处理工具类。
  • 相关阅读:
    [py]你真的了解多核处理器吗? 了解多线程
    [py]监控内存并出图
    [py]django强悍的数据库接口(QuerySet API)-增删改查
    【Unity Shaders】Transparency —— 透明的cutoff shader
    使用GDAL库中的RPC校正问题
    celery最佳实践
    Eclipse 快捷方式 指定 固定 workspace
    java 判断是否是周末
    如何设制 select 不可编辑 只读
    golang函数可变参数传递性能问题
  • 原文地址:https://www.cnblogs.com/monkjavaer/p/10312001.html
Copyright © 2020-2023  润新知