How to handle Internal server error (500) on spring rest API?

user3454581 :

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.

Bogdan Oros :
@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.

Guess you like

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