上一章我们用 onErrorResume 和 onErrorReturn 来处理 WebFlux 中的异常,但是这种处理方式效率不高,只能针对具体的方法。那么有没有和 SpringMVC 中的 @ControllerAdvice、@RestControllerAdvice 等相同功能的全局异常处理呢?
明确的告诉你,有!本文我们一起先来学习一个简单的吧!
先新建一个 XttblogRoute 类。
@Configuration
public class XttblogRoute {
@Bean
public RouterFunction<ServerResponse> xttblog() {
return route(GET("/xttblog"), req -> {
String param = req.queryParam("test").orElse(null);
if(null == param){
throw new XttblogException("www.xttblog.com 888");
}
return Mono.just("https://www.xttblog.com " + param).flatMap(s -> ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN).syncBody(s));
});
}
}
为了演示效果,我自定义一个异常处理类 XttblogException。
public class XttblogException extends RuntimeException{
private int code = 0;
private String msg = "";
public XttblogException() {
super();
}
public XttblogException(String msg) {
super(msg);
this.msg = msg;
}
public XttblogException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
// 省略其他 get/set 方法
}
然后全局异常处理,我们要借助 DefaultErrorAttributes 实现。DefaultErrorAttributes 是一个抽象类,在 SpringBoot 的 reactive 包中。
@Component
public class GlobalErrorAttributes extends DefaultErrorAttributes {
public GlobalErrorAttributes() {
super(false);
}
@Override
public Map<String, Object> getErrorAttributes(ServerRequest request,
boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(
request, includeStackTrace);
Throwable error = getError(request);
if (error instanceof XttblogException) {
errorAttributes.put("code", ((XttblogException) error).getCode());
errorAttributes.put("data", error.getMessage());
} else {
// 自定义一个 666
errorAttributes.put("code", 666);
errorAttributes.put("data", "www.xttblog.com ERROR");
}
return errorAttributes;
}
}
如果有多个 DefaultErrorAttributes 实现。可以使用 @Order() 来定义优先级。
启动类的代码和上一章中的相同,我就不在粘贴了。
项目启动后,我们在浏览器里请求 http://localhost:8080/xttblog,就会发生异常,被我们自定义的全局异常处理所拦截,返回 www.xttblog.com 888!如果请求中带有参数,类似这样:http://localhost:8080/xttblog?test=other 的正常请求,将返回正常的响应。
为了节约时间,运行效果我就不截图了,关于本博客的所有 WebFlux 教程源码,都可以在我的微信公众号里进行下载,回复”webflux“关键字即可!

: » WebFlux 的全局异常处理 DefaultErrorAttributes 详解
原创文章,作者:Carrie001128,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/251981.html