码迷,mamicode.com
首页 > 其他好文 > 详细

@ReponseStatus

时间:2020-05-02 00:09:59      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:ora   server   auto   web   obj   int   exist   object   repo   

@ResponseStatus

    @ResponseBody
   	//方法正常执行但是状态码变成400
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @RequestMapping("/test1")
    public String testRes() {
        return "你好 世界";
    }
	//如果加了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;
    }

@ReponseStatus

标签:ora   server   auto   web   obj   int   exist   object   repo   

原文地址:https://www.cnblogs.com/kikochz/p/12815314.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!