【发布时间】:2026-01-25 15:25:01
【问题描述】:
我无法让我的反应式代码以通用方式处理错误。理想的方式是使用可重用组件,我可以将其作为依赖项添加到其他项目中。
过去,我们使用@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);
}
}
在我们的公共库中:
@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();
}
我也尝试使用AbstractErrorWebExceptionHandler 与Baeldung 中的示例一样。似乎也不起作用:
@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 进行全局错误处理?
【问题讨论】:
标签: spring-webflux