【问题标题】:Global Exception handling in Spring reactor and dependent responsesSpring 反应器中的全局异常处理和相关响应
【发布时间】:2018-04-12 18:51:05
【问题描述】:

我正在尝试使用 spring 5 创建一个 Web 应用程序。这是一个微服务,几乎没有其他微服务。一个服务的响应依赖于另一个。我在我的应用程序中使用全局异常处理。

这是我的代码:

@Override
public Mono<Response> checkAvailablity(Request request) {
    Mono<Response> authResponse = userService.authenticateToken(request);
    return authResponse.doOnSuccess(t -> {
        // if success is returned.
        // Want to return this innerResponse
    Mono<Response> innerResponse = 
httpService.sendRequest(Constant.SER_BOOKING_SERVICE_CHECK_AVAILABILTY,
                request.toString(), Response.class);

    }).doOnError(t -> {
        logger.info("Subscribing mono in Booking service -  On Error");
        Mono.error(new CustomException(Constant.EX_MODULE_CONNECTION_TIMED_OUT));
    });

如果出现错误,我想抛出 CustomException 并在全局异常处理程序中捕获它:

@ControllerAdvice
public class ExceptionInterceptor {
public static Logger logger = Logger.getLogger(ExceptionInterceptor.class);

@ExceptionHandler(value = CustomException.class)
@ResponseBody
public Response authenticationFailure(ServerHttpRequest httpRequest, ServerHttpResponse response,
        CustomException ex) {
    logger.info("CustomException Occured with code => " + ex.getMessage());
    return buildErrorResponse(ex.getMessage());
}

基于上面的代码我有两个问题:

  1. 在 Mono.error() 中抛出的异常未在全局异常处理程序中捕获。
  2. 如果成功,应该返回来自内部服务的响应。

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

    在mono中使用了两种方法:flatmap()和onErrorMap()

    并更新了我的 checkAvailablity() 代码:

        public Mono<Response> checkAvailablity(Request request) {
        Mono<Response> authResponse = userService.authenticateToken(request);
        return authResponse.flatmap(t -> {
        // Added transform() for success case
        Mono<Response> response = httpService.sendRequest(Constant.SER_BOOKING_SERVICE_CHECK_AVAILABILTY,
                    request.toString(), Response.class);
            logger.info("Response from SER_BOOKING_SERVICE_CHECK_AVAILABILTY");
            return response;
        }).onErrorMap(t -> {
          // Added onErrorMap() for failure case & now exception is caught in global exception handler.
        throw new CustomException(Constant.EX_MODULE_CONNECTION_TIMED_OUT);
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-02
      • 2019-07-17
      • 2020-01-18
      • 2018-11-19
      • 2016-11-18
      • 2014-07-17
      • 2018-06-06
      • 2018-09-13
      相关资源
      最近更新 更多