I would like to handle multiple exceptions in the same way in the Controller of a Reactive Spring Boot API.
The idea is to send a HttpStatus.BAD_REQUEST
as an error response for more than one type of Exception
in the business logic.
My method ends something like this:
@PostMapping("/my-api")
public Mono<ResponseEntity<String>> save(@RequestBody JsonNode rawDto) {
return
myValidator.validate(rawDto)
.flatMap(validDto ->
myService.save(validDto))
.doOnSuccess(result->
new ResponseEntity<>(HttpStatus.OK))
.doOnError(MyValidationException.class, error->
new ResponseEntity<>(HttpStatus.BAD_REQUEST))
.doOnError(MyBusinessLogicException.class, error->
new ResponseEntity<>(HttpStatus.BAD_REQUEST))
.doOnError(MyRemoteApiException.class, error->
new ResponseEntity<>(HttpStatus.BAD_REQUEST))
.doOnError(MyDataConstraintException.class, error->
new ResponseEntity<>(HttpStatus.BAD_REQUEST)); // and so on
}
I would like to combine multiple exceptions in a single doOnError
block.
Something similar to this :
.doOnError(MyValidationException.class
| MyBusinessLogicException.class
| MyRemoteApiException.class, // and so on
error->
new ResponseEntity<>(HttpStatus.BAD_REQUEST))
I am not sure of any way to combine multiple exceptions.
I did not want to use if
condition before looking for a better option.
Any help is appreciated.
Thanks in advance.
As an option, using this overloaded version:
public final Flux<T> doOnError(Predicate<? super Throwable> predicate,
final Consumer<? super Throwable> onError)
With the Set
:
private final Set<Class<?>> errors = Set.of(
MyValidationException.class,
MyBusinessLogicException.class,
MyRemoteApiException.class,
MyDataConstraintException.class
)
...
.doOnSuccess(result-> new ResponseEntity<>(HttpStatus.OK))
.doOnError(
error -> errors.contains(error.getClass()), // <---- now this is one predicate
error-> new ResponseEntity<>(HttpStatus.BAD_REQUEST)
)
lo-fi wi-fi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.