Spring 3.2.15, MVC-based REST API (not Spring Download, unfortunately!). I am trying to implement an exception handler / handler that meets the following criteria:
- No matter what happens (success or failure), the Spring application always returns a response object
MyAppResponse(see below); and - If the request was processed successfully, return the HTTP status 200 (typical); and
- In the case of request processing and an exception occurs, I need to control the mapping of a specific exception to a specific HTTP status code
- Spring MVC environment errors (e.g.
BlahException) should map to HTTP 422 - User application exceptions, such as my
FizzBuzzException, have their own state mapping schemes:FizzBuzzException → HTTP 401FooBarException → HTTP 403OmgException → HTTP 404
- All other exceptions, that is, Spring exceptions and exceptions for non-standard applications (listed above 3), must contain HTTP 500
If the object MyAppResponse:
@Canonical
class MyAppResponse {
String detail
String randomNumber
}
It seems that it ResponseEntityExceptionHandlercan do this for me, but I do not see the forest through the wrt trees as it receives the arguments passed. I hope I can do something like:
@ControllerAdvice
class MyAppExceptionMapper extends ResponseEntityExceptionHandler {
ResponseEntity<Object> handleFizzBuzzException(FizzBuzzException fbEx, HttpHeaders headers, HttpStatus status) {
status = ???
new ResponseEntity(fbEx.message, headers, status)
}
ResponseEntity<Object> handleFooBarException(FooBarException fbEx, HttpHeaders headers, HttpStatus status) {
status = ???
new ResponseEntity(fbEx.message, headers, status)
}
ResponseEntity<Object> handleOmgException(OmgException omgEx, HttpHeaders headers, HttpStatus status) {
status = ???
new ResponseEntity(omgEx.message, headers, status)
}
ResponseEntity<Object> handleAllSpringExceptions(SpringException springEx, HttpHeaders headers, HttpStatus status) {
status = ???
new ResponseEntity(springEx.message, headers, status)
}
ResponseEntity<Object> handleAllOtherExceptions(Exception ex, HttpHeaders headers, HttpStatus status) {
status = ???
new ResponseEntity("Whoops, something happened. Lol.", headers, status)
}
}
Any idea how I can fully implement this matching logic and requiring the object to be an instance MyAppResponse, not just a string?
Then, annotates the class with the @ControllerAdviceonly thing I need to do to configure Spring to use it?