How can I customize the response status code and the data in the response body if an exception occurs in a Spring Boot web application?
I have created a web app that throws a custom exception if something unexpected occurs due to some bad internal state. Consequently, the response body of the request that triggered the error looks something like:
HTTP/1.1 500 Internal Server Error
{
"timestamp": 1412685688268,
"status": 500,
"error": "Internal Server Error",
"exception": "com.example.CustomException",
"message": null,
"path": "/example"
}
Now, I would like to change the status code and set the fields in the response body. One solution that crossed my mind was something like:
@ControllerAdvice
class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
ErrorMessage handleBadCredentials(CustomException e) {
return new ErrorMessage("Bad things happened");
}
}
@XmlRootElement
public class ErrorMessage(
private String error;
public ErrorMessage() {
}
public ErrorMessage(String error) {
this.error = error;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
)
However, that created (as suspected) a completely different response:
HTTP/1.1 400 Bad Request
{
"error": "Bad things happened"
}