38

Good day,

I am working on spring rest api and i would like to sure everything is working fine. I would like to log abnormal behaviors like nullPointerException or database connection error or any Exception that could raise and not handled or not assumed.

I would like to catch any unhandled exception and show a beautifull message to user instead of printing stack trace.

for this i found a solution on internet that is extend ResponseEntityExceptionHandler and override handleExceptionInternal method.

I also like to log 404 errors to see if someone trying to attack on my server.

I have also added this line in properties file : spring.mvc.throw-exception-if-no-handler-found=true

and here is the code for handleExceptionInternal

@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {

    GenericResponse response = new GenericResponse();
    response.setMessage("Internal error occured, " + ex.getStackTrace()[0]);

    System.out.println("big exceptions");

    return new ResponseEntity(response, headers, status);

}

My problem is when i am passing incorrect route like /abc this code is running fine, But when i throw null pointer exception from controllers method this method is not catching it.

thanks.

user3454581
  • 532
  • 1
  • 4
  • 11
  • Spring is not handling `NullPointerException` by default. If you check `ResponseEntityExceptionHandler`, you will see a list with handled exceptions. You can extend implement `HandlerExceptionResolver` and implement a custom logic (do not forget to map your method with `@ExceptionHandler(NullPointerException.class)`. For example, [Spring Data Rest](https://github.com/spring-projects/spring-data-rest/blob/master/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestExceptionHandler.java) has a custom handler, run through. – Bogdan Oros Jan 29 '18 at 19:25
  • i dont care if its null exception or not i just like ho work on all kind of exception like Exception class – user3454581 Jan 29 '18 at 19:30
  • 1
    As you can see the spring realizations, just mark your method with `@ExceptionHandler(RuntimeException.class)` - this way is very generic way and it forces you to `instanceof` your exceptions. – Bogdan Oros Jan 29 '18 at 19:34
  • can you please show some code snippet. if that works i will accept that answer i am really stuck here. – user3454581 Jan 29 '18 at 19:36
  • ControllerAdvice is the way to go – JPRLCol Jan 29 '18 at 19:59

1 Answers1

46
@ControllerAdvice
public class Handler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handle(Exception ex, 
                HttpServletRequest request, HttpServletResponse response) {
        if (ex instanceof NullPointerException) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

ExceptionHandler Documenation - here you can find all objects the method signature can operate with.

ControllerAdvice - with no additional properties it will handle all exceptions, so it can provide unexpected behavior. It's better to provide a package (your package) to basePackages property and it will handle only exceptions thrown in specified package.

Also it is a good practice to separate Exceptions to custom @ExceptionHandler marked methods, it will decouple the handlers logic.

Bogdan Oros
  • 1,249
  • 9
  • 13
  • can you please help me in one more thing i am also using public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) when Nullpointer exception is thrown ex is still null. – user3454581 Jan 29 '18 at 20:08
  • Because Spring exception handling is not involved on Filter Stage of request processing. The only possible way I saw in practice (a bit crunchy) - is to use a [ExceptionHandlingFilter](https://stackoverflow.com/questions/34595605/how-to-manage-exceptions-thrown-in-filters-in-spring) – Bogdan Oros Jan 29 '18 at 20:13