springboot 默认异常返回机制

本文解析了SpringBoot框架中对于不同来源的错误请求如何进行区分处理:来自浏览器的请求返回HTML页面,而非浏览器请求则返回JSON格式的错误信息。通过深入分析源码揭示了这一机制的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、背景

一个错误的url请求springboot会根据请求是从浏览器发出来的还是不是浏览器发出来的发出来的出现不同的返回:
浏览器发出来的:返回html代码
error-isb

不是浏览器发出来的:返回json
error-nob

二、原因

为什么会出现这种状况呢?看springboot源码中 org.springframework.boot.autoconfigure.web.BasicErrorController :它是springboot中默认错误的处理器。该类上面有两个注解:

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")

说明:它本身是controller,处理/error 这种请求,而它下面有两个requestMapping注解的方法:


    @RequestMapping(produces = "text/html")
    public ModelAndView errorHtml(HttpServletRequest request,
            HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
                request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
        return (modelAndView != null ? modelAndView : new ModelAndView("error", model));
    }

    @RequestMapping
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(body, status);
    }

从上面的代码可以看出,前一个questMapping中有produces = "text/html" 表示:请求头中的Content-Type参数包含text/html的时候,进入该方法,若没有包含,则进入另一个方法。

前一个方法会返回一个HTML, 后一个方法加了@ResponseBody注解,把一个map转换为json返回。

这就是springboot对浏览器和非浏览器发出请求出现异常,返回不同的原因。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值