Reputation: 29
Is there a way to catch all exceptions at once that are thrown from a web request in a Spring Boot Exception Handler? I know I can catch an array of Exception types in my method annotated with @ExceptionHandler
but it's not the types I'm talking about. I need something like a list of Exception objects. I already tried
@@ExceptionHandler({ MethodArgumentTypeMismatchException.class, ConstraintViolationException.class })
@ResponseBody
private Error handleException(final List<Exception> ex, WebRequest request) {
...
}
but Spring is not able to find a suitable resolver for that:
java.lang.IllegalStateException: Could not resolve parameter [0] in private com.example.demo.model.Error com.example.demo.exception.MyExceptionHandler.handleException(java.util.List<java.lang.Exception>,org.springframework.web.context.request.WebRequest): No suitable resolver
With catching only one Throwable object it works fine:
@ExceptionHandler({ MethodArgumentTypeMismatchException.class, ConstraintViolationException.class })
@ResponseBody
private Error handleException(final Exception ex, WebRequest request) {
...
}
But what to do if I have different parameter violations like e.g. a ConstraintViolationException
and a MethodArgumentTypeMismatchException
in the same request?
If it's not possible to process a list of exceptions, how can I satisfy RFC-7807 (see https://www.rfc-editor.org/rfc/rfc7807)? Which means: How can I collect all invalid parameters, no matter what's the causing exception?
Upvotes: 0
Views: 3017
Reputation: 51
@ExceptionHandler
public ResponseEntity<String> handle(Exception ex) {
// ...
}
you will catch most general exception. Then you can get suppressed https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Throwable.html#getSuppressed()
you cant throw more than one exception at once
Upvotes: 1
Reputation: 4623
I don't know about the annotation, but to catch multiple exceptions you do (remember that the first matching catch
block will execute):
@ResponseBody
public MyError handleException(List<Throwable> exceptions, WebRequest request) {
try {
//...
} catch (ConstraintViolationException e) {
//...
} catch (MethodArgumentTypeMismatchException e) {
//...
}
}
Upvotes: 0