如何在Spring中直接从HandlerExceptionResolver返回错误响应

时间:2017-11-10 07:03:00

标签: java spring angular exception-handling

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

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

    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.");
    

1 个答案:

答案 0 :(得分:0)

您可以扩展类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
}