@ReponseStatus

@ResponseStatus

    @ResponseBody
   	//方法正常执行但是状态码变成400
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @RequestMapping("/test1")
    public String testRes() {
        return "你好 世界";
    }

且不会跳转到4xx页面

	//如果加了reason属性reason就一定会发出异常(sendError), 而异常的statusCode就是400
	@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "请求不可用")
    @RequestMapping("/test3")
    public String testSuccess() {
        return "success";
    }
    //如果方法内部异常,状态码不会被改变
	@ResponseBody
    @ResponseStatus(HttpStatus.CONTINUE)//100
    @RequestMapping("/test4")
    public void testStatusCode() {
        throw new RuntimeException();
    }

与@ExceptionHandler一起使用, 抛出异常, 但是无法将map的值传递出去, 即使重写了org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes

    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR, reason = "请求不可用")
    @ExceptionHandler(UserNotExistException.class)
    private ModelAndView handleUserNotExistException1(UserNotExistException e) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("customer", "用户名不存在");
        map.put("msg",e.getMessage());
        return new ModelAndView("forward:/error", map);

可以通过指定javax.servlet.error.status_code将值传递到request中

        @ExceptionHandler(UserNotExistException.class)
        private ModelAndView handleUserNotExistException2(UserNotExistException e, HttpServletRequest request) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("customer", "用户名不存在");
            request.setAttribute("javax.servlet.error.status_code", HttpStatus.INTERNAL_SERVER_ERROR);
            return new ModelAndView("forward:/error", map);
        }

public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Object map = webRequest.getAttribute("customer", RequestAttributes.SCOPE_REQUEST);
        //保留原有的attr
        Map<String, Object> superAttr = super.getErrorAttributes(webRequest, includeStackTrace);
        superAttr.put("map", map);
        superAttr.put("info", "这是一条信息");
        return superAttr;
    }

如果将@ResponseStatus加在异常类上(不管有没有reason), 在抛出异常时被@ExceptionHandler捕获时, 方法还是会send对应statusCode的erro,
效果与在@Exception上加@ResponseStatus一样

posted @ 2020-05-01 23:11  CyberPelican  阅读(192)  评论(0编辑  收藏  举报