How to catch all unhandled exceptions (i.e. without existing @ExceptionHandler) in Spring MVC?

membersound :

I want to let HandlerExceptionResolver resolve any Exceptions that I don't explicit catch via @ExceptionHandler annotation.

Anyways, I want to apply specific logic on those exceptions. Eg send a mail notification or log additionally. I can achieve this by adding a @ExceptionHandler(Exception.class) catch as follows:

@RestControllerAdvice
public MyExceptionHandler {
    @ExceptionHandler(IOException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object io(HttpServletRequest req, Exception e) {
        return ...
    }


    @ExceptionHandler(Exception.class)
    public Object exception(HttpServletRequest req, Exception e) {
        MailService.send();
        Logger.logInSpecificWay();

        //TODO how to continue in the "normal" spring way with HandlerExceptionResolver?
    }
}

Problem: if I add @ExceptionHandler(Exception.class) like that, I can catch those unhandled exceptions.

BUT I cannot let spring continue the normal workflow with HandlerExceptionResolver to create the response ModelAndView and set a HTTP STATUS code automatically.

Eg if someone tries a POST on a GET method, spring by default would return a 405 Method not allowed. But with an @ExceptionHandler(Exception.class) I would swallow this standard handling of spring...

So how can I keep the default HandlerExceptionResolver, but still apply my custom logic?

membersound :

To provide a complete solution: it works just by extending ResponseEntityExceptionHandler, as that handles all the spring-mvc errors. And the ones not handled can then be caught using @ExceptionHandler(Exception.class).

@RestControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> exception(Exception ex) {
        MailService.send();
        Logger.logInSpecificWay();
        return ... custom exception 
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=439464&siteId=1