• 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);
            }
        }
  • 相关阅读:
    代码搭建记事本框架(一)
    代码搭建记事本框架(二)
    ios中图片拉伸用法
    ios启动载入启动图片
    Top-k test
    leetcode : jump game
    leetcode : Top k frequent elements
    一个月没有更新了
    leetcode : Reverse Linked List II [two pointers]
    leetcode : reverse linked list [基本功,闭着眼也要写出来]
  • 原文地址:https://www.cnblogs.com/dgwblog/p/11977784.html
Copyright © 2020-2023  润新知