【问题标题】:Java: Custom Global exception handler always returns 200 statusJava:自定义全局异常处理程序始终返回 200 状态
【发布时间】:2016-04-16 03:01:52
【问题描述】:

我为我的程序创建了一个全局异常处理程序,它正在运行并捕获我的异常,但是当我尝试从 HttpServletResponse 获取状态代码时,我总是得到 200 状态。有什么办法可以从异常类中获得正确的状态?或者,如果您有其他工作,我将不胜感激。在网上找不到任何东西,我不想为通过我的处理程序的每个异常硬编码 httpStatus。我想用这种方法捕获所有异常。这是我在 GlobalExceptionHandler 类中创建的方法(仅供参考,我为该类使用了 @ControllerAdvice 注释):

@ExceptionHandler(value = Exception.class)
public @ResponseBody
ResponseEntity<Object> error(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {

    log.error("Error in call to " + request.getRequestURI() + " Response: " + response.toString(), e);

    ExceptionResource exception = new ExceptionResource();
    exception.setLocation(request.getRequestURI());
    exception.setStatus(response.getStatus());
    exception.setStackTrace(e.getStackTrace());

    return new ResponseEntity<>(exception, HttpStatus.valueOf(response.getStatus()));
}

【问题讨论】:

    标签: java rest exception-handling


    【解决方案1】:

    如果你使用 Spring MVC,你的异常需要有这样的东西:

    @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")
    public class OrderNotFoundException extends RuntimeException {
        // ...
    }
    

    source

    【讨论】:

      【解决方案2】:

      回答:我不得不考虑另一种实现,但我确实找到了一种方法来获取使用 @ResponseStatus 注释创建的自定义异常的状态。您将希望使用它来获取状态:

       HttpStatus status = AnnotationUtils.findAnnotation(exception.getClass(), ResponseStatus.class).value();
      

      其中 exception 是传递给处理程序的异常。

      【讨论】:

        猜你喜欢
        • 2019-12-28
        • 2022-10-19
        • 2018-12-07
        • 2010-12-05
        • 1970-01-01
        • 2020-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多