to keep the json error generated by spring boot
best (i think):
like :
@ControllerAdvice
class MyAdvice extends ResponseEntityExceptionHandler {
// ...
}
(this is aware of your application.properties
..esp. spring.webflux.problemdetails.enabled
)
To custom handle "common exceptions"
just changing the status according to the exception type
Override the according handleXXXException
method, in this(400) scenario e.g. (handleResponseStatusException
):
@ControllerAdvice
class MyAdvice extends ResponseEntityExceptionHandler {
@Override
protected Mono<ResponseEntity<Object>> handleResponseStatusException(
ResponseStatusException ex, HttpHeaders headers, HttpStatusCode status,
ServerWebExchange exchange) {
// do what you need/like:
HttpStatusCode myNewStatus;
/*
switch (status.value()) { // alternatively: if (status.isXXX()) [else if .. else ..]
...
}*/
return /*super.*/handleExceptionInternal(ex, null, headers, myNewStatus, exchange);
}
}
To commonly handle "custom exceptions"
best:
Let your "custom exception" extend ErrorResponseException
:
class MyException extends ErrorResponseException {
public MyException(HttpStatusCode status) { // we need to override (at least 1) super constructor!
super(status);
}
}
Handle it with a custom exception handler (reusing parent methods;):
@ControllerAdvice
class MyAdvice extends ResponseEntityExceptionHandler {
// ...
@ExceptionHandler({MyException.class})
public Mono<ResponseEntity<Object>> handleMyException(MyException ex, ServerWebExchange exchange) {
return handleExceptionInternal(ex, null, ex.getHeaders(), ex.getStatusCode(), exchange);
}
// ...
}
For details, best: "browse" the javadoc, source code, "hierarchy structure" & "usages" of the mentioned classes.
The (springboot-webflux) default @ControllerAdvice/ResponseEntityExceptionHandler
is configured with org.springframework.boot.autoconfigure.web.reactive.ProblemDetailsExceptionHandler
.