Spring Boot優雅地處理404異常

程式設計師自由之路發表於2020-11-20

背景

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

雖然上面的返回很清楚,但是我們的介面需要返回統一的格式,比如:

{
    "rtnCode":"9999",
    "rtnMsg":"404 /hello/test1 Not Found"
}

這時候你可能會想有Spring的統一異常處理,在Controller類上加@RestControllerAdvice註解。但是這種做法並不能統一處理404錯誤。

404錯誤產生的原因

產生404的原因是我們調了一個不存在的介面,但是為什麼會返回下面的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會根據請求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;
}

這個方法沒什麼內容,直接是呼叫了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狀態從0設定成1
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        // 直接返回
        return;
    }
    ... 省略部分方法
}

這個方法很簡單,就是設定404響應碼,將Response的errorState狀態從0設定成1,然後就返回響應了。整個過程並沒有發生任何異常,所以不能觸發Spring的全域性異常處理機制

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

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

我們繼續往下看。Response響應被返回,進入org.apache.catalina.core.StandardHostValve類的invoke方法進行處理。(不要問我為什麼知道是在這裡?Debug的能力是需要自己摸索出來的,自己除錯多了,你也就會了)

@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;
        }
        // 在這裡判斷請求是不是發生了錯誤,錯誤的話就進入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);
    }
  }

這個方法會根據返回的響應判斷是不是發生了錯了,如果發生了error,則進入StandardHostValve的status(Request request, Response response)方法。這個方法“兜兜轉轉”又進入了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<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返回格式。我們繼續往下看。

到這邊為止,我們好像沒有任何線索了。但是如果仔細看上面日誌的話,你會發現這個介面的處理方法是:

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預設配置的一個Controller,預設處理/error請求。BasicErrorController提供兩種返回錯誤一種是頁面返回、當你是頁面請求的時候就會返回頁面,另外一種是json請求的時候就會返回json錯誤。

自定義404錯誤處理類

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

在IDEA中,檢視BasicErrorController的usage,我們發現這個類是在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<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);
    }

    /**
     * 覆蓋預設的HTML響應
     */
    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        //請求的狀態
        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);
    }
}

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

server:
  error:
    path: /xxx

更詳細的內容請參考Spring Boot的章節。

簡單總結

  • 如果在過濾器(Filter)中發生異常,或者呼叫的介面不存在,Spring會直接將Response的errorStatus狀態設定成1,將http響應碼設定為500或者404,Tomcat檢測到errorStatus為1時,會將請求重現forward到/error介面;
  • 如果請求已經進入了Controller的處理方法,這時發生了異常,如果沒有配置Spring的全域性異常機制,那麼請求還是會被forward到/error介面,如果配置了全域性異常處理,Controller中的異常會被捕獲;
  • 繼承BasicErrorController就可以覆蓋原有的錯誤處理方式。

相關文章