【问题标题】:How to return error response directly from HandlerExceptionResolver in springspring 如何直接从 HandlerExceptionResolver 返回错误响应
【发布时间】:2018-04-23 08:40:01
【问题描述】:

我已经定义了一个全局异常处理程序,如下所示。它可以毫无问题地处理异常。问题是我使用 spring 作为我的角度后端,所以我不想返回 ModelAndView 对象。我的问题是;

  1. 我不希望在全局处理程序之后由任何其他类处理异常。
  2. 我想直接从全局错误处理程序返回响应。

全局异常处理程序。

public class GlobalExceptionHandler implements HandlerExceptionResolver, Ordered {
    public int getOrder() {
        return Integer.MIN_VALUE; 
    }

    public ModelAndView resolveException(
        HttpServletRequest aReq, HttpServletResponse aRes,
        Object aHandler, Exception ex
    ) {
         // i want to add something like below code here
        return null; // if i return null here, the next handler is triggered. I don`t want to do that. I want program to stop here and return a response.

    }
}

我希望能够使用以下代码直接从全局处理程序返回响应

           aRes.reset();
           aRes.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
           aRes.setHeader("Access-Control-Allow-Credentials", "true");
           aRes.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE");
           aRes.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization, Content-Type, Accept, enctype");
           aRes.sendError(ErrorCodes.UNAUTHORIZED_USER, "The service is booting.");

【问题讨论】:

    标签: java spring angular exception-handling


    【解决方案1】:

    您可以扩展类ResponseEntityExceptionHandler 并使用@ControllerAdvice 注释对其进行注释。在这里,您可以通过覆盖现有的受保护方法来自定义如何处理特定的 Spring web 异常,例如:

     @Override
     protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status,
      WebRequest request) {
        // Do anything you want here with the httpheaders and just return a ResponseEntity with an null body
     }
    

    如果需要,你可以在这个类中添加额外的方法来处理你自己的异常类型,例如:

    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public ResponseEntity<ErrorInfo> handleApplicationException(ApplicationException applicationException) {
       // Called for our own application exception
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 2011-11-16
      相关资源
      最近更新 更多