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);
            }
        }
  • 相关阅读:
    Linux之文件处理命令
    Linux基础命令
    rip实验
    Linux基础之磁盘分区
    mysql安装
    centos Apache、php、mysql默认安装路径
    You probably tried to upload too large file. Please refer to documentation for ways to workaround this limit.
    Wrong permissions on configuration file, should not be world writable!
    机器会学习么 学习总结
    实验 5 Spark SQL 编程初级实践
  • 原文地址:https://www.cnblogs.com/dgwblog/p/11977784.html
Copyright © 2011-2022 走看看