2.spring系列之404异常的捕获

回顾

我在之前发布了一篇spring统一返回的文章,最后提到是无法捕获404异常的,这里我们先来测试一下

@RestController
public class TestController {
   

    @GetMapping("/test")
    public String insert22() {
   
        return "hello";
    }
}

浏览器请求试一下 http://localhost:8080/xxx 报错

# Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Dec 29 10:14:36 CST 2021

There was an unexpected error (type=Not Found, status=404).

springboot的处理方式

springboot处理这个404的异常是在 BasicErrorController中处理的

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
   

	...........

	@Override
	public String getErrorPath() {
   
		return null;
	}

	@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
	public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
   
		HttpStatus status = getStatus(request);
		Map<String, Object> model = Collections
				.unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
		response.setStatus(status.value());
		ModelAndView modelAndView = resolveErrorView(request, response, status, model);
		return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
	}
	
	// 包含请求头 "Accept": "application/json" 会往这里走
	@RequestMapping
	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
   
		HttpStatus status = getStatus(request);
		if (status == HttpStatus.NO_CONTENT) {
   
			return new ResponseEntity<>(status);
		}
		Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
		return new ResponseEntity<>(body, status);
	}
	
	.............
}

只要请求路径/error就可以进去到errorHtml这个方法,在浏览器请求http://localhost:8080/error就可以进入这个方法

解决方案

我这使用的springboot的版本为2.3.7.RELEASE

方案1:重写/error的请求

这种方案会直接舍弃掉HTML响应方式,但是前后端分离模式下,后端已经很少使用ModelAndView了

@Controller
public class NoFoundController extends AbstractErrorController {
   

    public NoFoundController(ErrorAttributes errorAttributes) {
   
        super(errorAttributes);
    }

    /**
     * 默认路径/error,可以通过server.error.path配置
     */
    @RequestMapping(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值