简体   繁体   中英

How to return error response directly from HandlerExceptionResolver in spring

I have defined a global exception handler like below. It cathces the exceptions with no problem. The problem is i am using spring as my angular backend so i don`t want to return a ModelAndView Object. My problems are;

  1. I don`t want the exception handled by any other classes after global handler.
  2. I want to return a response directly from the global error handler.

The 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.

    }
}

I want to be able to return a response using the below code, directly from global handler

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

You can extend the class ResponseEntityExceptionHandler and annotate it with a @ControllerAdvice annotation. In here, you can customize how specific Spring web exceptions can be handled by overriding the existing protected methods, eg:

 @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
 }

If needed, you can add additional methods to this class to handle your own types of exceptions, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM