12

我有一个 @ControllerAdvice 扩展 ResponseEntityExceptionHandler 作为我尝试控制 API 调用工作流中引发的任何异常的标准响应。

没有控制器的建议。我得到了 spring 生成的基于 HTML 的通用响应,并带有正确的响应标头。但是当我添加我的@ControllerAdvice 时,Spring 不会以通用错误主体响应。正文为空且响应头正确

@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {

        String erroMessage = "Required Parameter: '"+ex.getParameterName()+"' was not available in the request.";
        TrsApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, erroMessage, ex, ApiErrorCode.INVALID_REQUEST);
        return buildResponseEntity(apiError);
}

因此,现在,如果请求中缺少必需的参数,流程会完美地触发我的重写实现,并使用描述错误的 JSON 有效负载进行响应。但是,如果出现任何其他异常,例如 HttpMediaTypeNotAcceptableException,spring 会以空主体响应。

在我添加我的建议之前,spring 以通用错误响应进行响应。我是 Spring Boot 生态系统的新手。需要帮助了解这是否是预期行为,是否有更好的方法来实现集中错误处理。

4

3 回答 3

6

我想我在 ControllerAdvice 类扩展时找到了吞下身体的解决方案ResponeEntityExceptionHandler。在我的情况下,设置如下所示:

@ControllerAdvice
@Slf4j
class GlobalExceptionHandlers extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
                                      MethodArgumentNotValidException exception,
                                      HttpHeaders headers,
                                      HttpStatus status,
                                      WebRequest request) {
        // logic that creates apiError object (object with status, message, errorCode, etc)
        //...
        return handleExceptionInternal(exception, apiError, headers, status, request);
    }

这对于 class 的例外来说就像一个魅力MethodArgumentNotValidException。但它破坏了由 处理的所有其他异常ResponseEntityExceptionHandler,并为它们返回了空的响应正文。

但修复很简单,只需覆盖handleExceptionInternalfrom ResponseEntityExceptionHandler

@ControllerAdvice
@Slf4j
class GlobalExceptionHandlers extends ResponseEntityExceptionHandler {

    /// ... code from previous snippet

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(
                                      Exception exception, 
                                      Object body, 
                                      HttpHeaders headers, 
                                      HttpStatus status, 
                                      WebRequest request) {
        // for all exceptions that are not overriden, the body is null, so we can
        // just provide new body based on error message and call super method
        var apiError = Objects.isNull(body) 
                ? new ApiError(status, exception.getMessage()) // <-- 
                : body;
        return super.handleExceptionInternal(exception, apiError, headers, status, request);
    }
}
于 2020-04-28T19:48:29.580 回答
2

这是预期的行为。查看类 ResponseEntityExceptionHandler 的源代码。

@ExceptionHandler({
            org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            HttpMediaTypeNotAcceptableException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            MethodArgumentNotValidException.class,
            MissingServletRequestPartException.class,
            BindException.class,
            NoHandlerFoundException.class,
            AsyncRequestTimeoutException.class
        })
    public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) {

所有这些异常都是在没有响应主体的情况下处理的。调用了一个通用方法:

//second parameter is body which is null
handleExceptionInternal(ex, null, headers, status, request)

如果您需要以不同方式处理特定异常,请覆盖它们,例如我想为HttpMessageNotReadableException发送自定义响应

 @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request)
    {
        logger.error("handleHttpMessageNotReadable()", ex);
        ValidationErrors validationErrors = null;
        if (ex.getRootCause() instanceof InvalidFormatException) {
            InvalidFormatException jacksonDataBindInvalidFormatException = (InvalidFormatException) ex.getRootCause();
            validationErrors = new ValidationErrors(jacksonDataBindInvalidFormatException.getOriginalMessage());
        }
        headers.add("X-Validation-Failure", "Request validation failed !");
        return handleExceptionInternal(ex, validationErrors, headers, status, request);
    }
于 2019-06-10T15:01:42.200 回答
0

使用@ControllerAdvice 后,您需要定义通用异常结构。

@ResponseBody
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse generationExceptionHandler(Exception e){
    log.info("Responding INTERNAL SERVER ERROR Exception");
    return new ErrorResponse(ServiceException.getSystemError());
}
于 2019-06-10T14:55:55.577 回答