gpt4 book ai didi

java - 在spring-webflux中处理错误的正确方法是什么

转载 作者:行者123 更新时间:2023-12-03 23:28:00 25 4
gpt4 key购买 nike

我一直在使用spring-webflux进行一些研究,我想了解使用路由器功能处理错误的正确方法。

我创建了一个小项目来测试几个场景,并且我希望获得有关它的反馈,并查看其他人在做什么。

到目前为止,我在做什么。

提供以下路由功能:

@Component
public class HelloRouter {
@Bean
RouterFunction<?> helloRouterFunction() {
HelloHandler handler = new HelloHandler();
ErrorHandler error = new ErrorHandler();

return nest(path("/hello"),
nest(accept(APPLICATION_JSON),
route(GET("/"), handler::defaultHello)
.andRoute(POST("/"), handler::postHello)
.andRoute(GET("/{name}"), handler::getHello)
)).andOther(route(RequestPredicates.all(), error::notFound));
}
}

我已经在我的处理程序上执行了
class HelloHandler {

private ErrorHandler error;

private static final String DEFAULT_VALUE = "world";

HelloHandler() {
error = new ErrorHandler();
}

private Mono<ServerResponse> getResponse(String value) {
if (value.equals("")) {
return Mono.error(new InvalidParametersException("bad parameters"));
}
return ServerResponse.ok().body(Mono.just(new HelloResponse(value)), HelloResponse.class);
}

Mono<ServerResponse> defaultHello(ServerRequest request) {
return getResponse(DEFAULT_VALUE);
}

Mono<ServerResponse> getHello(ServerRequest request) {
return getResponse(request.pathVariable("name"));
}

Mono<ServerResponse> postHello(ServerRequest request) {
return request.bodyToMono(HelloRequest.class).flatMap(helloRequest -> getResponse(helloRequest.getName()))
.onErrorResume(error::badRequest);
}
}

它们是我的错误处理程序:
class ErrorHandler {

private static Logger logger = LoggerFactory.getLogger(ErrorHandler.class);

private static BiFunction<HttpStatus,String,Mono<ServerResponse>> response =
(status,value)-> ServerResponse.status(status).body(Mono.just(new ErrorResponse(value)),
ErrorResponse.class);

Mono<ServerResponse> notFound(ServerRequest request){
return response.apply(HttpStatus.NOT_FOUND, "not found");
}

Mono<ServerResponse> badRequest(Throwable error){
logger.error("error raised", error);
return response.apply(HttpStatus.BAD_REQUEST, error.getMessage());
}
}

这是完整的示例存储库:

https://github.com/LearningByExample/reactive-ms-example

最佳答案

Spring 5提供了一个WebHandler,在JavaDoc中有以下一行:

Use HttpWebHandlerAdapter to adapt a WebHandler to an HttpHandler. The WebHttpHandlerBuilder provides a convenient way to do that while also optionally configuring one or more filters and/or exception handlers.



当前,官方文档建议我们在启动任何服务器之前将路由器功能包装到HttpHandler中:
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction);

借助 WebHttpHandlerBuilder,我们可以配置自定义异常处理程序:
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(toHttpHandler(routerFunction))
.prependExceptionHandler((serverWebExchange, exception) -> {

/* custom handling goes here */
return null;

}).build();

关于java - 在spring-webflux中处理错误的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43575538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com