0

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

z8manu8z
  • 15
  • 1
  • 6
  • Are you throwing exceptions by yourself or you're also handling the run-time exceptions? – Pallav Jha Mar 16 '16 at 07:49
  • I didn't ask myself the question ... but handling both will be better. – z8manu8z Mar 16 '16 at 07:57
  • then you can use Exception.getMessage() method for exceptions thrown by you, considering, you are passing the message in constructor while throwing exceptions. – Pallav Jha Mar 16 '16 at 08:04

0 Answers0