在一个基于响应式框架的Spring引导Rest控制器中,如何配置,在全局层面(类似于Spring mvc中的全局异常处理程序),根据应用内抛出的异常类型的错误响应状态仍然保持Spring引导产生的json错误?
例如,如果抛出IllegalArgumentException,则响应将是:
HTTP/1.1 400 Bad Request
Content-Type: application/json
Content-Length: 191
{
"timestamp": "2023-04-05T06:52:30.521+00:00",
"path": "request/path",
"status": 400,
"error": "Bad Request",
"requestId": "876c0e0b-1"
}
而不是默认值:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
Content-Length: 191
{
"timestamp": "2023-04-05T06:52:30.521+00:00",
"path": "request/path",
"status": 500,
"error": "Internal Server Error",
"requestId": "876c0e0b-1"
}
谢啦
保留Spring Boot生成的json错误
最好(我认为):
喜欢:
@ControllerAdvice
class MyAdvice extends ResponseEntityExceptionHandler {
// ...
}
(这是知道你的application.properties
… esp.Spring.webflux.有问题的细节。启用
)
只是根据异常类型改变状态
覆盖根据handleXXXException
方法,在这(400)种情况下,例如(handleResponse seStatusException
):
@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);
}
}
最佳:
>
让您的“自定义异常”扩展错误响应异常
:
class MyException extends ErrorResponseException {
public MyException(HttpStatusCode status) { // we need to override (at least 1) super constructor!
super(status);
}
}
使用自定义异常处理程序处理它(重用父方法;):
@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);
}
// ...
}
详情最好:“浏览”javadoc、源代码、“层次结构”
使用org. springframe.boot.autoconfiure.web.react.ProblemDetailsExceptionHandler
配置(springboot-web通)默认@ControlllerAd不建议/响应EntityExceptionHandler
。