Smart Developer
Smart Developer

Reputation: 43

Exception is not thrown for page doesn't exist

I have defined ExceptionHandler with @ControllerAdvice and catches the following

Exception.class, Throwable.class, SQLException.class

When a user enters a page which doesn't exist or not available in the server. circular view page error is being displayed in the log and ExceptionHandler is not getting called.

What are the usual checkpoints to make the API error to get caught in CustomExceptionHandler. Not sure whether any tomcat hooks to be defined.

Using Spring Boot 2.0 and Spring version 5.0

Thanks.

Upvotes: 1

Views: 87

Answers (1)

The Mighty Programmer
The Mighty Programmer

Reputation: 1252

In case : user enters a page/resource which does not exist, no exception is thrown. So your code does not work (I believe your code is similar to following code)

@ControllerAdvice
public class ErrorHandler {
    @ExceptionHandler(Exception.class) 
    public String handle() {
     ....
     return "error"
    }

}

In order to make it work you need to extend yourhandler class from ResponseEntityExceptionHandler as

@ControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {

   ...

}

And You need to override the following method

  • handleHttpMediaTypeNotSupported
  • handleHttpMediaTypeNotSupported

Detailed guide can be found from
- https://blog.jayway.com/2013/02/03/improve-your-spring-rest-api-part-iii/
- http://www.baeldung.com/global-error-handler-in-a-spring-rest-api

Another way, You can override /error if there is fixed message in all general cases.

Upvotes: 1

Related Questions