SpringBoot中默认的错误处理机制

前言

springboot项目快速搭建完成后,在浏览器端通过正确的请求地址能获取到我们想要数据然而通过不正确的请求地址访问到的会是类似以下的错误信息页面:


而通过发送http请求工具,类似postman、restlet client等,该文使用restlet client返回结果为:


跟踪源码,以上的错误信息来自BasicErrorController处理结果,该类中有两个处理方法,分别处理以上页面请求错误和restlet请求错误。

       @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 ? new ModelAndView("error", model) : modelAndView);
	}
        //非页面请求异常处理
	@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);
	}

但在实际开发中返回的错误提示页面,我希望对用户能友好的展示,上文中的错误信息主要是给开发人员阅读的。

实际错误页面的查找逻辑为,假如请求为查找顺序为 404页面 => 4XX页面 => error页面,4XX的意思是404、405等以4开头的状态找的都是4XX页面。这里就不列出我是怎么得到这个逻辑的,感兴趣的同学只需debugger跟着代码逻辑走就能找到以上结论。

页面配置路径如下:


浏览器端发送404请求,返回我们自定义的页面。


猜你喜欢

转载自blog.csdn.net/fu250/article/details/80291298