需求:出现意外报错响应内容可读性差,不利于排查与定位,需要自定义错误响应。
在web中可以使用@ControllerAdvice即可编写统一异常响应,在webFlux下则是另一种编写方式。
Component
@Order(-2) //这里将全局错误处理程序的顺序设置为-2。这是为了让它比 @Order(-1) 注册的 DefaultErrorWebExceptionHandler 处理程序更高的优先级。
@Slf4j
public class ExceptionHandler implements ErrorWebExceptionHandler {
@SneakyThrows
@Override
public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
ServerHttpResponse response = serverWebExchange.getResponse();
response.setStatusCode(HttpStatus.OK);
Dson dson = new Dson();
String message = throwable.getMessage();
dson.put("错误信息:", message);
String methodValue = serverWebExchange.getRequest().getMethodValue();
dson.put("请求方式:", methodValue);
return serverWebExchange.getRequest().getBody()
.collectList()
.flatMap(list -> {
log.info("list:{}", list);
StringBuffer str = new StringBuffer();
for (DataBuffer buf : list) {
byte[] bytes = new byte[buf.readableByteCount()];
buf.read(bytes);
str.append(new String(bytes));
}
dson.put("消息体:", str.toString());
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
DataBuffer buff = response.bufferFactory().wrap(dson._Value().toString().getBytes());//非池化内存
return response.writeWith(Mono.just(buff));
});
}
}
效果演示
请求方式:post
请求地址:localhost:11000/error
请求体:
{
"账号":"152xxxxxxx",
"token":"356434371b1a7a984d37a1f4f3054c8b",
}
请求方法:
@RequestMapping("/error")
public Object getError(String Str) {
return 1/0;
}
原生错误响应:
{
"timestamp": 1598952492292,
"path": "/error",
"status": 500,
"error": "Internal Server Error",
"message": "/ by zero",
"requestId": "af25e175-1"
}
自定义错误响应:
{
"错误信息:": "/ by zero",
"请求方式:": "POST",
"消息体:": {
"账号": "152xxxxxxxx",
"token": "356434371b1a7a984d37a1f4f3054c8b"
}
}