【问题标题】:Java Spring @ExceptionHandler are not handling errors correctlyJava Spring @ExceptionHandler 没有正确处理错误
【发布时间】:2016-12-16 11:41:19
【问题描述】:

我有问题然后我尝试捕获异常。

这是我实现 ResponseErrorHandler 的类:

    public class ErrorGenerator implements ResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        ServiceError error = objectMapper.readValue(response.getBody(), ServiceError.class);

String message = "Test"


    ValidationException exception = new ValidationException(error);

    throw exception;
    }

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return true;
    }
}

ValidationException 扩展了 ServiceException,后者扩展了 RuntimeException。

这是我的@ControllerAdvice 类

@ExceptionHandler(ServiceException.class)
public ServiceError handleException(ServiceException exception) {
return exception.getError();
}

我收到的错误说:

Exception thrown in handleError: {}

我将不胜感激。

【问题讨论】:

  • 这可以编译吗? ValidationException 异常 = new ValidationException(,error);
  • 我认为您需要 HttpServletRequest request 作为方法中的参数:handleException(HttpServletRequest request, ServiceException exception)
  • 对不起,错误。 :)
  • @PauChorro 你几乎是对的,我将返回类型更改为 ResponseEntity 并且它工作正常。谢谢!

标签: java spring exception exception-handling


【解决方案1】:

需要通过参数HttpServletRequest request 传递,正如@Laurynas 建议的那样,它应该返回ResponseEntity<?>。所以解决方案如下:

    @ExceptionHandler(ServiceException.class)
    public ServiceError handleException(HttpServletRequest request, ServiceException exception) {
         return new ResponseEntity<ServiceError>(exception.getError());
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2019-12-03
    • 2019-10-02
    相关资源
    最近更新 更多