zoukankan      html  css  js  c++  java
  • Spring Boot 处理异常返回json

    spring boot 老版本处理异常  对于浏览器客户端,返回error数据

    对于非浏览器返回json数据, 主要取决于你的请求head 是什么 

    但是当我们自定义了:  老版本无论请求什么都会返回json异常数据,

    @ControllerAdvice
    public class UserExceptionHandler {
    
        @ResponseBody
        @ExceptionHandler(UserNotFoundExits.class)
        public Map<String, Object> handleException(Exception e){
            Map<String,Object> map = new HashMap<>();
            map.put("code","user.notexist");
            map.put("message",e.getMessage());
            return map;
        }
    }

     通过阅读源码, 新版本的异常处理 就是我们上面强制定义了 异常处理类 ,也会按照 浏览器返回error ,客户端返回json 

        @RequestMapping(
            produces = {"text/html"}
        )
        public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
            HttpStatus status = this.getStatus(request);
            Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
            response.setStatus(status.value());
            ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
            return modelAndView != null ? modelAndView : new ModelAndView("error", model);
        }
    
        @RequestMapping
        public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
            HttpStatus status = this.getStatus(request); // 此处做了更改
            if (status == HttpStatus.NO_CONTENT) {
                return new ResponseEntity(status);
            } else {
                Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
                return new ResponseEntity(body, status);
            }
        }
  • 相关阅读:
    Hadoop源代码分析(五)
    使用Solr Data Import的deltaimport功能
    hbasewriter
    Hadoop源代码分析(四)
    lucene .NET 搜索图片 功能实现
    char类型与string类型的区别
    Windows程序设计:'SM_ MOUSEWHEELPRESENT' : undeclared identifier解决办法
    汇编里的栈空间
    在汇编源程序中,数据不能以字母开头
    中值
  • 原文地址:https://www.cnblogs.com/dgwblog/p/11977784.html
Copyright © 2011-2022 走看看