<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Spring Boot優(yōu)雅地處理404異常

          共 12267字,需瀏覽 25分鐘

           ·

          2020-11-22 14:48

          點擊上方藍色字體,選擇“標星公眾號”

          優(yōu)質(zhì)文章,第一時間送達

          ? 作者?|??程序員自由之路

          來源 |? urlify.cn/Mv2Avq

          66套java從入門到精通實戰(zhàn)課程分享

          背景

          在使用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;
          ????}
          }

          當我們使用錯誤的請求地址(POST http://127.0.0.1:8888/hello/test1?id=98)進行請求時,會報下面的錯誤:

          {
          ??"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。

          我們直接進入到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)方法。所以直接進入這個方法看下吧。

          @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");
          ????????//?這個方法很簡單,就是設置404響應碼,然后將Response的errorState狀態(tài)從0設置成1
          ????????response.sendError(HttpServletResponse.SC_NOT_FOUND);
          ????????//?直接返回
          ????????return;
          ????}
          ????...?省略部分方法
          }

          這個方法很簡單,就是設置404響應碼,將Response的errorState狀態(tài)從0設置成1,然后就返回響應了。整個過程并沒有發(fā)生任何異常,所以不能觸發(fā)Spring的全局異常處理機制

          到這邊還有一個問題沒有解決:就是下面的404提示信息是怎么返回的。

          {
          ??"timestamp":?"2020-11-19T08:30:48.844+0000",
          ??"status":?404,
          ??"error":?"Not?Found",
          ??"message":?"No?message?available",
          ??"path":?"/hello/test1"
          }

          我們繼續(xù)往下看。Response響應被返回,進入org.apache.catalina.core.StandardHostValve類的invoke方法進行處理。(不要問我為什么知道是在這里?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ā)生了錯誤,錯誤的話就進入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ù)返回的響應判斷是不是發(fā)生了錯了,如果發(fā)生了error,則進入StandardHostValve的status(Request request, Response response)方法。這個方法“兜兜轉(zhuǎn)轉(zhuǎ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;
          ????????}
          ????}

          上面標號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>?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ù)往下看。

          到這邊為止,我們好像沒有任何線索了。但是如果仔細看上面日志的話,你會發(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?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>?error(HttpServletRequest?request)?{
          ????????Map?body?=?getErrorAttributes(request,
          ????????????????isIncludeStackTrace(request,?MediaType.ALL));
          ????????HttpStatus?status?=?getStatus(request);
          ????????return?new?ResponseEntity>(body,?status);
          ????}
          ????...?省略部分方法
          }

          BasicErrorController是Spring默認配置的一個Controller,默認處理/error請求。BasicErrorController提供兩種返回錯誤一種是頁面返回、當你是頁面請求的時候就會返回頁面,另外一種是json請求的時候就會返回json錯誤。

          自定義404錯誤處理類

          我們先看下BasicErrorController是在哪里進行配置的。

          在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());
          ????}

          ????/**
          ?????*?覆蓋默認的JSON響應
          ?????*/
          ????@Override
          ????public?ResponseEntity>?error(HttpServletRequest?request)?{

          ????????HttpStatus?status?=?getStatus(request);
          ????????Map?map?=?new?HashMap(16);
          ????????Map?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,?status);
          ????}

          ????/**
          ?????*?覆蓋默認的HTML響應
          ?????*/
          ????@Override
          ????public?ModelAndView?errorHtml(HttpServletRequest?request,?HttpServletResponse?response)?{
          ????????//請求的狀態(tài)
          ????????HttpStatus?status?=?getStatus(request);
          ????????response.setStatus(getStatus(request).value());
          ????????Map?model?=?getErrorAttributes(request,
          ????????????????isIncludeStackTrace(request,?MediaType.TEXT_HTML));
          ????????ModelAndView?modelAndView?=?resolveErrorView(request,?response,?status,?model);
          ????????//指定自定義的視圖
          ????????return?(modelAndView?==?null???new?ModelAndView("error",?model)?:?modelAndView);
          ????}
          }

          默認的錯誤路徑是/error,我們可以通過以下配置進行覆蓋:

          server:
          ??error:
          ????path:?/xxx

          更詳細的內(nèi)容請參考Spring Boot的章節(jié)。

          簡單總結(jié)

          • 如果在過濾器(Filter)中發(fā)生異常,或者調(diào)用的接口不存在,Spring會直接將Response的errorStatus狀態(tài)設置成1,將http響應碼設置為500或者404,Tomcat檢測到errorStatus為1時,會將請求重現(xiàn)forward到/error接口;

          • 如果請求已經(jīng)進入了Controller的處理方法,這時發(fā)生了異常,如果沒有配置Spring的全局異常機制,那么請求還是會被forward到/error接口,如果配置了全局異常處理,Controller中的異常會被捕獲;

          • 繼承BasicErrorController就可以覆蓋原有的錯誤處理方式。






          粉絲福利:實戰(zhàn)springboot+CAS單點登錄系統(tǒng)視頻教程免費領取

          ???

          ?長按上方微信二維碼?2 秒
          即可獲取資料



          感謝點贊支持下哈?

          瀏覽 34
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  亚洲视频天天射 | 亚洲色婷 | 日韩中文字幕网站 | 99视频在线观看免费 | 8x8x国产一区二区三区精品痛苦 |