gpt4 book ai didi

spring-webflux - 使用 RouterFunction 处理 WebFlux 中的错误

转载 作者:行者123 更新时间:2023-12-04 08:27:41 50 4
gpt4 key购买 nike

我无法让我的响应式(Reactive)代码以一种常见的方式处理错误。理想的方式是使用可重用的组件,我可以将其作为依赖项添加到其他项目中。

过去,我们使用 @RestControllerAdvise 通过个性化的 @ExceptionHandler 函数来处理它们。作为引用,我的代码:

@Configuration
public class VesselRouter {

@Bean
public RouterFunction<ServerResponse> route(VesselHandler handler) {
return RouterFunctions.route(GET("/vessels/{imoNumber}").and(accept(APPLICATION_JSON)), handler::getVesselByImo)
.andRoute(GET("/vessels").and(accept(APPLICATION_JSON)), handler::getVessels);
}
}

此外,处理程序类:
@Component
@AllArgsConstructor
public class VesselHandler {
private VesselsService vesselsService;

public Mono<ServerResponse> getVesselByImo(ServerRequest request) {
String imoNumber = request.pathVariable("imoNumber");
Mono<VesselResponse> response = this.vesselsService.getByImoNumber(imoNumber);
return response.hasElement().flatMap(vessel -> {
if (vessel) {
return ServerResponse.ok()
.contentType(APPLICATION_JSON)
.body(response, VesselResponse.class);
} else {
throw new DataNotFoundException("The data you seek is not here.");
}
}
);

}

public Mono<ServerResponse> getVessels(ServerRequest request) {
return this.vesselsService.getAllVessels();
}
}
/**
* Exception class to be thrown when data not found for the requested resource
*/
public class DataNotFoundException extends RuntimeException {

public DataNotFoundException(String e) {
super(e);
}
}

在我们的公共(public)库中:
@ControllerAdvice(assignableTypes={VesselHandler.class})
// FIXME: referencing class here is not good, it will create circular dependency when moved to it's own jar
@Slf4j
public class ExceptionHandlers {

@ExceptionHandler(value = DataNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<String> handleDataNotFoundException(DataNotFoundException dataNotFoundException,
ServletWebRequest servletWebRequest) {
//habdling expcetions code here
}
}

还有异常处理程序:
@ControllerAdvice
@Slf4j
public class ExceptionHandlers {

@ExceptionHandler(value = DataNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<String> handleDataNotFoundException(DataNotFoundException dataNotFoundException,
ServletWebRequest servletWebRequest) {
//habdling expcetions code here
}
}

我在 spring documentation 中读到,这是它应该工作的方式,但我的单元测试似乎并没有靠近异常处理程序:
@Test
public void findByImoNoData() {
when(vesselsService.getByImoNumber("1234567")).thenReturn(Mono.empty());
webTestClient.get().uri("/vessels/1234567")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isNotFound();
}

我还尝试使用 AbstractErrorWebExceptionHandlerBaeldung 中的示例一样。似乎也不起作用:
@Component
@Order(-2)
public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {

public GlobalErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext) {
super(errorAttributes, resourceProperties, applicationContext);
}

@Override
protected RouterFunction<ServerResponse> getRoutingFunction(
ErrorAttributes errorAttributes) {

return RouterFunctions.route(
RequestPredicates.all(), this::renderErrorResponse);
}

private Mono<ServerResponse> renderErrorResponse(
ServerRequest request) {

Map<String, Object> errorPropertiesMap = getErrorAttributes(request, false);

return ServerResponse.status(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(errorPropertiesMap));
}
}

那么,如何在不使用 @RestController 的情况下使用 WebFlux 进行全局错误处理?

最佳答案

@ControllerAdvice仅适用于带注释的编程模型。提供类似 ControllerAdvice 的功能使用功能端点,您可以利用 HandlerFilterFunction .从引用:

Routes mapped by a router function can be filtered by calling RouterFunction.filter(HandlerFilterFunction), where HandlerFilterFunction is essentially a function that takes a ServerRequest and HandlerFunction, and returns a ServerResponse. The handler function parameter represents the next element in the chain: this is typically the HandlerFunction that is routed to, but can also be another FilterFunction if multiple filters are applied. With annotations, similar functionality can be achieved using @ControllerAdvice and/or a ServletFilter.



@Bean
RouterFunction<ServerResponse> route() {
return RouterFunctions
.route(GET("/foo"), request -> Mono.error(new DataNotFoundException()))
.andRoute(GET("/bar"), request -> Mono.error(new DataNotFoundException()))
.filter(dataNotFoundToBadRequest());
}

private HandlerFilterFunction<ServerResponse, ServerResponse> dataNotFoundToBadRequest() {
return (request, next) -> next.handle(request)
.onErrorResume(DataNotFoundException.class, e -> ServerResponse.badRequest().build());
}

或者,您可以使用 WebFilter 来完成同样的事情:

@Bean
RouterFunction<ServerResponse> route() {
return RouterFunctions
.route(GET("/foo"), request -> Mono.error(new DataNotFoundException()))
.andRoute(GET("/bar"), request -> Mono.error(new DataNotFoundException()));
}

@Bean
WebFilter dataNotFoundToBadRequest() {
return (exchange, next) -> next.filter(exchange)
.onErrorResume(DataNotFoundException.class, e -> {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.BAD_REQUEST);
return response.setComplete();
});
}

关于spring-webflux - 使用 RouterFunction 处理 WebFlux 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51931178/

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