摘要
Spring Cloud 2020.0.3有两种常用方式处理错误:自定义全局错误属性或者完整的DefaultErrorWebExceptionHandler。前者更为简洁,后者更为全面。
正文
版本号: Spring Cloud 2020.0.3
普遍的方式 有 完成自身的 DefaultErrorWebExceptionHandler 或 仅完成ErrorAttributes.
方式 1: ErrorWebExceptionHandler (仅作提示)
自定一个 GlobalErrorAttributes:
@Component
public class GlobalErrorAttributes extends DefaultErrorAttributes{
@Override
public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
Throwable error = super.getError(request);
Map<String, Object> map = super.getErrorAttributes(request, options);
map.put("status", HttpStatus.BAD_REQUEST.value());
map.put("message", error.getMessage());
return map;
}
}
完成一个
@Component
@Order(-2)
public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {
public GlobalErrorWebExceptionHandler(GlobalErrorAttributes gea, ApplicationContext applicationContext,
ServerCodecConfigurer serverCodecConfigurer) {
super(gea, new WebProperties.Resources(), applicationContext);
super.setMessageWriters(serverCodecConfigurer.getWriters());
super.setMessageReaders(serverCodecConfigurer.getReaders());
}
//3D渲染html或json
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(final ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) {
final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, ErrorAttributeOptions.defaults());
return ServerResponse.status(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(errorPropertiesMap));
}
}
方式 2, 仅完成一个 ErrorAttributes, 以遮盖默认设置的 DefaultErrorAttributes
//Spring 默认设置的就很好了.
@Component
public class GatewayErrorAttributes extends DefaultErrorAttributes {
private static final Logger logger = LoggerFactory.getLogger(GatewayErrorAttributes.class);
@Override
public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
Throwable error = super.getError(request);
Map<String, Object> errorAttributes = new HashMap<>(8);
errorAttributes.put("message", error.getMessage());
errorAttributes.put("method", request.methodName());
errorAttributes.put("path", request.path());
MergedAnnotation<ResponseStatus> responseStatusAnnotation = MergedAnnotations
.from(error.getClass(), MergedAnnotations.SearchStrategy.TYPE_HIERARCHY).get(ResponseStatus.class);
HttpStatus errorStatus = determineHttpStatus(error, responseStatusAnnotation);
//务必设定, 不然会出错, 由于 DefaultErrorWebExceptionHandler 的 renderErrorResponse 方式 会获得此特性, 再次完成 DefaultErrorWebExceptionHandler也可.
errorAttributes.put("status", errorStatus.value());
errorAttributes.put("code", errorStatus.value());
//html view用
errorAttributes.put("timestamp", new Date());
//html view 用
errorAttributes.put("requestId", request.exchange().getRequest().getId());
errorAttributes.put("error", errorStatus.getReasonPhrase());
errorAttributes.put("exception", error.getClass().getName());
return errorAttributes;
}
//从DefaultErrorWebExceptionHandler中拷贝回来的
private HttpStatus determineHttpStatus(Throwable error, MergedAnnotation<ResponseStatus> responseStatusAnnotation) {
if (error instanceof ResponseStatusException) {
return ((ResponseStatusException) error).getStatus();
}
return responseStatusAnnotation.getValue("code", HttpStatus.class).orElse(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
那样就可以了.
留意留意: 务必设定 errorAttributes.put(“status”, errorStatus.value()) , 不然会出错, 由于 DefaultErrorWebExceptionHandler 的 renderErrorResponse 方式 会获得此特性. 除非是你自己像方式 一一样再次完成 DefaultErrorWebExceptionHandler.
随后在网关ip中浏览一个不会有的服务项目, 就可以见到实际效果.
curl 'http://127.0.0.1:8900/fundmain22/abc/gogogo?id=1000' --header 'Accept: application/json'
{"exception":"org.springframework.web.server.ResponseStatusException","path":"/fundmain22/abc/gogogo","code":404,"method":"GET","requestId":"094e53e5-1","message":"404 NOT_FOUND","error":"Not Found","status":404,"timestamp":"2021-08-09T11:07:44.106 0000"}
谢谢互联网上的各种各样文章内容…
文中来源于博客园,创作者:飞云~风之谷,转截请标明全文连接:https://www.cnblogs.com/cnscud/p/15120406.html
关注不迷路
扫码下方二维码,关注宇凡盒子公众号,免费获取最新技术内幕!
温馨提示:如果您访问和下载本站资源,表示您已同意只将下载文件用于研究、学习而非其他用途。
评论0