0

对于运行 Spring Boot 1.5.2 的 Spring Boot 应用程序,我有一个类似于以下内容的 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 响应代码是什么?

4

1 回答 1

0

Spring 会抛出一个500 Internal Server Error,因为发生了异常并且没有正确处理。

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

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

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

于 2021-01-11T23:31:53.010 回答