使用RouterFunction在WebFlux中处理错误

时间:2018-08-20 12:51:41

标签: spring-webflux

我无法使我的反应式代码以常见方式处理错误。理想的方法是将一个可重用的组件添加为其他项目中的依赖项。

过去,我们使用@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进行全局错误处理?

2 个答案:

答案 0 :(得分:4)

@ControllerAdvice仅用于带注释的编程模型。要为功能端点提供类似ControllerAdvice的功能,您可以利用HandlerFilterFunction。从参考:

  

可以通过调用RouterFunction.filter(HandlerFilterFunction)过滤由路由器功能映射的路由,其中​​HandlerFilterFunction本质上是一个接受ServerRequest和HandlerFunction并返回ServerResponse的功能。 handler函数参数代表链中的下一个元素:这通常是路由到的HandlerFunction,但如果应用了多个过滤器,也可以是另一个FilterFunction。通过注释,可以使用@ControllerAdvice和/或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();
            });
}

答案 1 :(得分:2)

对我来说,我组成了一个AppException并将其抛出到应用程序(Rest控制器)中我认为应该是“错误”响应的任何位置。

  • AppException:我的特定异常,它可以包含您要处理,显示,返回错误的任何内容。

    public class AppException extends RuntimeException {
        int code;
        HttpStatus status = HttpStatus.OK;
        ...
    }
    

然后我定义(a)全局ControllerAdvice,它负责过滤掉这些AppException。

这是我的示例,我可以取出抛出在Rest控制器中的AppException,然后将其作为ReponseEntity返回,并将主体作为“ ErrorResponse” POJO。

public class ErrorResponse {

    boolean error = true;
    int code;
    String message;
}

@ControllerAdvice
public class GlobalExceptionHandlingControllerAdvice {

    @ExceptionHandler(AppException.class)
    public ResponseEntity handleAppException(AppException ex) {
        return ResponseEntity.ok(new ErrorResponse(ex.getCode(), ex.getMessage()));
    }
}

在webflux中,返回Rob。Winch作为答案可能会返回Mono.error()来引发错误。