Spring Boot優(yōu)雅地處理404異常問題
背景
在使用SpringBoot的過程中,你肯定遇到過404錯誤。比如下面的代碼:
@RestController @RequestMapping(value = "/hello") public class HelloWorldController { @RequestMapping("/test") public Object getObject1(HttpServletRequest request){ Response response = new Response(); response.success("請求成功..."); response.setResponseTime(); return response; } }
當(dāng)我們使用錯誤的請求地址(POST http://127.0.0.1:8888/hello/test1?id=98)進(jìn)行請求時,會報下面的錯誤:
{ "timestamp": "2020-11-19T08:30:48.844+0000", "status": 404, "error": "Not Found", "message": "No message available", "path": "/hello/test1" }
雖然上面的返回很清楚,但是我們的接口需要返回統(tǒng)一的格式,比如:
{ "rtnCode":"9999", "rtnMsg":"404 /hello/test1 Not Found" }
這時候你可能會想有Spring的統(tǒng)一異常處理,在Controller類上加@RestControllerAdvice注解。但是這種做法并不能統(tǒng)一處理404錯誤。
404錯誤產(chǎn)生的原因
產(chǎn)生404的原因是我們調(diào)了一個不存在的接口,但是為什么會返回下面的json報錯呢?我們先從Spring的源代碼分析下。
{ "timestamp": "2020-11-19T08:30:48.844+0000", "status": 404, "error": "Not Found", "message": "No message available", "path": "/hello/test1" }
為了代碼簡單起見,這邊直接從DispatcherServlet的doDispatch方法開始分析。(如果不知道為什么要從這邊開始,你還要熟悉下SpringMVC的源代碼)。
... 省略部分代碼.... // Actually invoke the handler. mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); ... 省略部分代碼
Spring MVC會根據(jù)請求URL的不同,配置的RequestMapping的不同,為請求匹配不同的HandlerAdapter。
對于上面的請求地址:http://127.0.0.1:8888/hello/test1?id=98匹配到的HandlerAdapter是HttpRequestHandlerAdapter。
我們直接進(jìn)入到HttpRequestHandlerAdapter中看下這個類的handle方法。
@Override @Nullable public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { ((HttpRequestHandler) handler).handleRequest(request, response); return null; }
這個方法沒什么內(nèi)容,直接是調(diào)用了HttpRequestHandler類的handleRequest(request, response)方法。所以直接進(jìn)入這個方法看下吧。
@Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // For very general mappings (e.g. "/") we need to check 404 first Resource resource = getResource(request); if (resource == null) { logger.trace("No matching resource found - returning 404"); // 這個方法很簡單,就是設(shè)置404響應(yīng)碼,然后將Response的errorState狀態(tài)從0設(shè)置成1 response.sendError(HttpServletResponse.SC_NOT_FOUND); // 直接返回 return; } ... 省略部分方法 }
這個方法很簡單,就是設(shè)置404響應(yīng)碼,將Response的errorState狀態(tài)從0設(shè)置成1,然后就返回響應(yīng)了。整個過程并沒有發(fā)生任何異常,所以不能觸發(fā)Spring的全局異常處理機(jī)制。
到這邊還有一個問題沒有解決:就是下面的404提示信息是怎么返回的。
{ "timestamp": "2020-11-19T08:30:48.844+0000", "status": 404, "error": "Not Found", "message": "No message available", "path": "/hello/test1" }
我們繼續(xù)往下看。Response響應(yīng)被返回,進(jìn)入org.apache.catalina.core.StandardHostValve類的invoke方法進(jìn)行處理。(不要問我為什么知道是在這里?Debug的能力是需要自己摸索出來的,自己調(diào)試多了,你也就會了)
@Override public final void invoke(Request request, Response response) throws IOException, ServletException { Context context = request.getContext(); if (context == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext")); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(context.getPipeline().isAsyncSupported()); } boolean asyncAtStart = request.isAsync(); boolean asyncDispatching = request.isAsyncDispatching(); try { context.bind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER); if (!asyncAtStart && !context.fireRequestInitEvent(request.getRequest())) { return; } try { if (!asyncAtStart || asyncDispatching) { context.getPipeline().getFirst().invoke(request, response); } else { if (!response.isErrorReportRequired()) { throw new IllegalStateException(sm.getString("standardHost.asyncStateError")); } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); container.getLogger().error("Exception Processing " + request.getRequestURI(), t); if (!response.isErrorReportRequired()) { request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); } } response.setSuspended(false); Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); if (!context.getState().isAvailable()) { return; } // 在這里判斷請求是不是發(fā)生了錯誤,錯誤的話就進(jìn)入StandardHostValve的status(Request request, Response response)方法。 // Look for (and render if found) an application level error page if (response.isErrorReportRequired()) { if (t != null) { throwable(request, response, t); } else { status(request, response); } } if (!request.isAsync() && !asyncAtStart) { context.fireRequestDestroyEvent(request.getRequest()); } } finally { // Access a session (if present) to update last accessed time, based // on a strict interpretation of the specification if (ACCESS_SESSION) { request.getSession(false); } context.unbind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER); } }
這個方法會根據(jù)返回的響應(yīng)判斷是不是發(fā)生了錯了,如果發(fā)生了error,則進(jìn)入StandardHostValve的status(Request request, Response response)方法。這個方法“兜兜轉(zhuǎn)轉(zhuǎn)”又進(jìn)入了StandardHostValve的custom(Request request, Response response,ErrorPage errorPage)方法。這個方法中將請求重新forward到了"/error"接口。
private boolean custom(Request request, Response response, ErrorPage errorPage) { if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("Processing " + errorPage); } try { // Forward control to the specified location ServletContext servletContext = request.getContext().getServletContext(); RequestDispatcher rd = servletContext.getRequestDispatcher(errorPage.getLocation()); if (rd == null) { container.getLogger().error( sm.getString("standardHostValue.customStatusFailed", errorPage.getLocation())); return false; } if (response.isCommitted()) { rd.include(request.getRequest(), response.getResponse()); } else { // Reset the response (keeping the real error code and message) response.resetBuffer(true); response.setContentLength(-1); // 1: 重新forward請求到/error接口 rd.forward(request.getRequest(), response.getResponse()); response.setSuspended(false); } return true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); container.getLogger().error("Exception Processing " + errorPage, t); return false; } }
上面標(biāo)號1處的代碼重新將請求forward到了/error接口。所以如果我們開著Debug日志的話,你會在后臺看到下面的日志。
[http-nio-8888-exec-7] DEBUG org.springframework.web.servlet.DispatcherServlet:891 - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/error]
2020-11-19 19:04:04.280 [http-nio-8888-exec-7] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping:313 - Looking up handler method for path /error
2020-11-19 19:04:04.281 [http-nio-8888-exec-7] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping:320 - Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2020-11-19 19:04:04.281 [http-nio-8888-exec-7] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory:255 - Returning cached instance of singleton bean 'basicErrorController'
上面是/error的請求日志。到這邊還是沒說明為什么能返回json格式的404返回格式。我們繼續(xù)往下看。
到這邊為止,我們好像沒有任何線索了。但是如果仔細(xì)看上面日志的話,你會發(fā)現(xiàn)這個接口的處理方法是:
org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
我們打開BasicErrorController這個類的源代碼,一切豁然開朗。
@Controller @RequestMapping("${server.error.path:${error.path:/error}}") public class BasicErrorController extends AbstractErrorController { @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); } ... 省略部分方法 }
BasicErrorController是Spring默認(rèn)配置的一個Controller,默認(rèn)處理/error請求。BasicErrorController提供兩種返回錯誤一種是頁面返回、當(dāng)你是頁面請求的時候就會返回頁面,另外一種是json請求的時候就會返回json錯誤。
自定義404錯誤處理類
我們先看下BasicErrorController是在哪里進(jìn)行配置的。
在IDEA中,查看BasicErrorController的usage,我們發(fā)現(xiàn)這個類是在ErrorMvcAutoConfiguration中自動配置的。
@Configuration @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass({ Servlet.class, DispatcherServlet.class }) // Load before the main WebMvcAutoConfiguration so that the error View is available @AutoConfigureBefore(WebMvcAutoConfiguration.class) @EnableConfigurationProperties({ ServerProperties.class, ResourceProperties.class }) public class ErrorMvcAutoConfiguration { @Bean @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT) public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) { return new BasicErrorController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers); } ... 省略部分代碼 }
從上面的配置中可以看出來,只要我們自己配置一個ErrorController,就可以覆蓋掉BasicErrorController的行為。
@Controller @RequestMapping("${server.error.path:${error.path:/error}}") public class CustomErrorController extends BasicErrorController { @Value("${server.error.path:${error.path:/error}}") private String path; public CustomErrorController(ServerProperties serverProperties) { super(new DefaultErrorAttributes(), serverProperties.getError()); } /** * 覆蓋默認(rèn)的JSON響應(yīng) */ @Override public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { HttpStatus status = getStatus(request); Map<String, Object> map = new HashMap<String, Object>(16); Map<String, Object> originalMsgMap = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); String path = (String)originalMsgMap.get("path"); String error = (String)originalMsgMap.get("error"); String message = (String)originalMsgMap.get("message"); StringJoiner joiner = new StringJoiner(",","[","]"); joiner.add(path).add(error).add(message); map.put("rtnCode", "9999"); map.put("rtnMsg", joiner.toString()); return new ResponseEntity<Map<String, Object>>(map, status); } /** * 覆蓋默認(rèn)的HTML響應(yīng) */ @Override public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { //請求的狀態(tài) HttpStatus status = getStatus(request); response.setStatus(getStatus(request).value()); Map<String, Object> model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); ModelAndView modelAndView = resolveErrorView(request, response, status, model); //指定自定義的視圖 return (modelAndView == null ? new ModelAndView("error", model) : modelAndView); } }
默認(rèn)的錯誤路徑是/error,我們可以通過以下配置進(jìn)行覆蓋:
server: error: path: /xxx
更詳細(xì)的內(nèi)容請參考Spring Boot的
簡單總結(jié)#
- 如果在過濾器(Filter)中發(fā)生異常,或者調(diào)用的接口不存在,Spring會直接將Response的errorStatus狀態(tài)設(shè)置成1,將http響應(yīng)碼設(shè)置為500或者404,Tomcat檢測到errorStatus為1時,會將請求重現(xiàn)forward到/error接口;
- 如果請求已經(jīng)進(jìn)入了Controller的處理方法,這時發(fā)生了異常,如果沒有配置Spring的全局異常機(jī)制,那么請求還是會被forward到/error接口,如果配置了全局異常處理,Controller中的異常會被捕獲;
- 繼承BasicErrorController就可以覆蓋原有的錯誤處理方式。
到此這篇關(guān)于Spring Boot優(yōu)雅地處理404異常的文章就介紹到這了,更多相關(guān)Spring Boot 404異常內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring中@RestController和@Controller的區(qū)別小結(jié)
@RestController和@Controller這兩個注解用于創(chuàng)建Web應(yīng)用程序的控制器類,那么這兩個注解有哪些區(qū)別,本文就來介紹一下,并用示例代碼說明,感興趣的可以了解一下2023-09-09淺析javax.servlet.Servlet,ServletContext接口
本篇文章是對javax.servlet.Servlet,ServletContext接口進(jìn)行了纖細(xì)的分析介紹,需要的朋友參考下2013-07-07SpringBoot項(xiàng)目集成Swagger和swagger-bootstrap-ui及常用注解解讀
這篇文章主要介紹了SpringBoot項(xiàng)目集成Swagger和swagger-bootstrap-ui及常用注解解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03