I'm trying to manage exceptions in a Spring MVC context and send different http statuses in response.
I tried this :
@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE)
public class UnavailableServiceException extends RuntimeException {
}
When I send this exception in my controller, it works fine : response http status is 503. But I want my controller to send json, and with this configuration, when 503 is send, response is html :-/
So I tried this :
Removing @ResponseStatus on my exception class and defining an Exception handler.
@ExceptionHandler(UnavailableServiceException.class)
public ResponseEntity<ExceptionJSONInfo> handleUnavailableService(UnavailableServiceException exception) {
return new ResponseEntity<ExceptionJSONInfo>(new ExceptionJSONInfo("Error xxx", exception.getMessage()), HttpStatus.SERVICE_UNAVAILABLE);
}
It's ok : 503 and json. But I want to manage 5 or 6 different exceptions : how can I do this without duplicating handlers ? Is it possible to retrieve @ResponseStatus defined on an exception ?
If not, my next idea will be to define an httpStatus attribute in a super class, mother of all my exceptions. And then :
public class UnavailableServiceException extends MySuperException {
super(HttpStatus.SERVICE_UNAVAILABLE);
}
@ExceptionHandler(MySuperException.class)
public ResponseEntity<ExceptionJSONInfo> handleUnavailableService(MySuperException exception) {
return new ResponseEntity<ExceptionJSONInfo>(new ExceptionJSONInfo("Error xxx", exception.getMessage()), exception.getHttpStatus());
}
Any better idea ?
Thanks
Manu