I use the following code to handle all exceptions of type RuntimeException
in class annotated with @ControllerAdvice
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<JSONObject> RuntimeExceptionHandler(RuntimeException e) throws JSONException {
JSONObject response = new JSONObject();
response.put("message", e.getMessage());
return new ResponseEntity<JSONObject>(response, HttpStatus.BAD_REQUEST);
}
It retuns the following response to the client in case of a ValidationException
:
{
"timestamp": 1496377230943,
"status": 500,
"error": "Internal Server Error",
"exception": "javax.validation.ValidationException",
"message": "Name does not meet expectations",
"path": "/signup"
}
It is not what I expected. The status code is not BAD_REQUEST
and the json is different from response
.
It works fine if I change JSONObject
to String
and pass in a string message instead of a json object. I also put a break point before return
statement and the response
looks fine.
Note: There is another post here which:
@ResponseBody
which I didn't.JSONObject
A quick fix if you require a returned JSON format:
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> RuntimeExceptionHandler(RuntimeException e) {
JSONObject response = new JSONObject();
response.put("message", e.getMessage());
return new ResponseEntity<String>(response.toString(), HttpStatus.BAD_REQUEST);
}