@RequestMapping 注释控制器中的运行时异常 - 哪个 HTTP 响应代码?

Runtime Exception in @RequestMapping annotated Controller - which HTTP Response Code?

对于 Spring Boot 应用程序,运行 Spring Boot 1.5.2,我有一个类似于以下内容的 handleRequest() 方法:

@RequestMapping(path = "/my/path/endpoint", method = RequestMethod.POST, consumes = { "text/*", "application/json" })
@ResponseStatus(HttpStatus.Accepted) 
public void handleRequest(@RequestBody String body, @RequestHeader(HttpHeaders.CONTENT_TYPE) Object contentType, @RequestHeader HttpHeaders headers) throws IllegalArgumentException, JsonProcessingException {
    if( //I'm missing a required header ) {
        throw new CustomExceptionThatExtendsRuntimeException("missing my header"); 
    }
    /* 
        do more stuff here
    */ 
}

如果我的 IF 语句为真并且我在方法主体中抛出 RuntimeException,那么返回的 HTTP 响应代码是什么?

Spring 将抛出 500 Internal Server Error,因为发生了异常并且未正确处理。

HandleExceptionResolver用于解决请求生命周期中抛出的异常。

如果发生异常,DispatcherServlet 委托一个 HandlerExceptionResolver bean 链来解决异常并通常提供错误响应。由于 Spring 不知道如何处理您的自定义异常,将抛出 HTTP 500 指示发生了内部错误。

您可以创建一个 HandlerExceptionResolver 的 bean 并注册到您的应用程序上下文,或者如果您想处理这些异常,可以使用 ControllerAdviceRestControllerAdvice