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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)