Return JSON on uncaught exceptions in Spring controllers Return JSON on uncaught exceptions in Spring controllers json json

Return JSON on uncaught exceptions in Spring controllers


For returning JSON on uncaught exceptions you can use this code:

import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestController;@ControllerAdvice  @RestControllerpublic class GlobalExceptionHandler {    private class JsonResponse {        String message;        public JsonResponse() {        }        public JsonResponse(String message) {            super();            this.message = message;        }        public String getMessage() {            return message;        }        public void setMessage(String message) {            this.message = message;        }           }    @ExceptionHandler(value = Exception.class)      public ResponseEntity<JsonResponse> handleException(Exception e) {        return new ResponseEntity<JsonResponse>(new JsonResponse(e.getMessage()), HttpStatus.BAD_REQUEST);    }}

JSON result if exception is throwing:

{    "message": "Something wrong!"}

You can use this link for more detailed information about Spring exception handling (with code examples).


HttpEntity represents an HTTP request or response consists of headers and body.

// Only talks about body & headers, but doesn't talk about status codepublic HttpEntity(T body, MultiValueMap<String,String> headers)

ResponseEntity extends HttpEntity but also adds a Http status code.

// i.e ResponseEntity = HttpEntity + StatusCodepublic ResponseEntity(T body, MultiValueMap<String,String> headers, HttpStatus statusCode)

Hence used to fully configure the HTTP response.

If you have a look at constructor of ResponseEntity you will see first parameter as body, i.e exactly where you can pass the object you want as body of http response when exception arrives