Luca Archidiacono
Luca Archidiacono

Reputation: 127

NullPointerException create own JSON response object

As I started to work with Spring REST Services I came across with NullPointerExceptions and their responses.

Due to some missing details/information I get from the NullPointerException (as a Client), I would like to create an own JSON Object which will be sent after each NullPointerException I get.

Is there any way to override the body of the NullPointerException ResponseEntity?

Thanks for your time ;)

Upvotes: 0

Views: 90

Answers (1)

csenga
csenga

Reputation: 4114

You should use ControllerAdvice for this. It can catch exceptions from the Controller beans and handle them.

In your case:

@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ResponseEntity<OwnError> handleGenericError(final NullPointerException exception) {

        OwnError ownError=new OwnError();
        ownError.set...

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ownError);
    }
}

This will return OwnError if your your Controller throws NullPointerException.

Upvotes: 2

Related Questions