美文网首页Spring
Spring 全局异常处理与定制ResponseBody

Spring 全局异常处理与定制ResponseBody

作者: PandaXiong | 来源:发表于2017-12-07 18:06 被阅读330次

    1.介绍ExceptionHandler与ControllerAdvice

    @ExceptionHandler
    注解到方法上,出现异常时会执行该方法。
    @ControllerAdvice
    使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常。

    1.处理局部异常(Controller内)

        @ExceptionHandler
        public ModelAndView exceptionHandler(Exception ex){
            ModelAndView mv = new ModelAndView("error");
            mv.addObject("exception", ex);
            return mv;
        }
    
    

    2.处理全局异常(所有Controller)

    @ControllerAdvice
    public class testControllerAdvice {
        @ExceptionHandler
        public ModelAndView exceptionHandler(Exception ex){
            ModelAndView mv = new ModelAndView("error");
            mv.addObject("exception", ex);
            return mv;
        }
    }
    

    2.定义统一的返回体

    现在基本都是前后端分离,后端只需要提供json接口。需要定制个通用返回体。

    {
            "msg": "操作成功",
            "success": true,
            "result":{
              },
            "code": 1
    }
    

    真正需要返回的数据在result里面。普通Controller返回的内容会被放在result里面。这样业务中不需要去考虑response,只需要返回数据,和抛出异常就行了。

    @ControllerAdvice(basePackages = "com.xiong")
    public class ResultResponseBodyAdvice implements ResponseBodyAdvice<Object>{
    
        private final static int successCode=1;//成功编码
        private final static int errorCode=0;//验证错误 (定义一个验证异常,验证失败抛异常,比如参数错误,主要验证前端参数)
        private final static int sysErrorCode=-1;//系统错误
        private final static String DefaultMsg="网络不给力,请稍后再试";
    
    
        @Override
        /**
         * 过滤是否是json的数据
         */
    
        public boolean supports(MethodParameter methodParameter, Class aClass) {
    
            Boolean isRest = AnnotationUtils.isAnnotationDeclaredLocally(
                    RestController.class, methodParameter.getContainingClass());
            ResponseBody responseBody = AnnotationUtils.findAnnotation(
                    methodParameter.getMethod(), ResponseBody.class); //得到方法上的注解
            if (isRest || responseBody != null) {
                return true;
            } else {
                return false;
            }
    
        }
    
        /**
         * 修改返回的数据
         */
        @Override
        public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
            if (o instanceof Result) {
                return o;
            }
            Result result = Result.getInstance();
            o = o==null?"":o;
            result.setResult(o);
            return result;
    
        }
    
    
    
        /**
         * 全局异常的处理
         * @param request
         * @param ex
         * @return
         */
        @ExceptionHandler(value = {Exception.class})
        @ResponseBody
        public Result handleAllException(HttpServletRequest request, Exception ex) {
    
            ex.printStackTrace();
            String msg = DefaultMsg;
            Integer code = errorCode;
            if (ex instanceof ValidationException) {
                ValidationException validationException = (ValidationException)ex;
                if (validationException.getCode() != null) {
                    code = validationException.getCode();
                }
                if (!StringUtils.isNullOrEmpty(validationException.getMessage())) {
                    msg = validationException.getMessage();
                }
            }
            Result response = new Result();
            response.setSuccess(false);
            response.setResult("");
            response.setCode(code);
            response.setMsg(msg);
            return response;
    
        }
    
    
        public static class Result {
            private String msg;
            private Boolean success;
            private Object result;
            private Integer code;
    
            public String getMsg() {
                return msg;
            }
    
            public Boolean getSuccess() {
                return success;
            }
    
            public Object getResult() {
                return result;
            }
    
            public Integer getCode() {
                return code;
            }
    
            public void setMsg(String msg) {
                this.msg = msg;
            }
    
            public void setSuccess(Boolean success) {
                this.success = success;
            }
    
            public void setResult(Object result) {
                this.result = result;
            }
    
            public void setCode(Integer code) {
                this.code = code;
            }
    
            public static Result getInstance() {
                Result result = new Result();
                result.setSuccess(true);
                result.setMsg("操作成功");
                result.setResult("");
                result.setCode(successCode);
                return result;
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:Spring 全局异常处理与定制ResponseBody

        本文链接:https://www.haomeiwen.com/subject/otdjixtx.html