【问题标题】:RxJava custom exception handling/propagation in spring boot rest applicationSpring Boot Rest 应用程序中的 RxJava 自定义异常处理/传播
【发布时间】:2017-07-31 12:34:54
【问题描述】:

我想知道 RxJava 和 spring REST API 最好的是什么?

我有一个简单的 REST 服务,并且在存储库中,如果出现错误,我想将特定的自定义错误传播给客户端。但我不确定如何使用 RxJava 映射不同的自定义异常。

这是对后端的调用:

private Single<Customer> findCustomerById(long customerId) {
    return Single.fromCallable(() -> getRestTemplate().getForObject(
            MyBackendService.SEARCH_CUSTOMER_BY_ID.getUrl(),
            Customer.class, customerId))
            .onErrorResumeNext(ex -> Single.error(new BackendException(ex)));
}

我的例外:

public class BackendException extends Exception {
public BackendException(String message) {
    super(message);
}

public BackendException(Throwable cause) {
    super(cause);
}

所以问题是如何用 RxJava 这个BackendException 映射/传播到让我们说NotFound (404) 或InternalServerError (500)?

【问题讨论】:

    标签: java spring rest rx-java


    【解决方案1】:

    我使用了异常库,这些异常库对于您care about 的每种 HTTP 响应类型都有异常,以及可以放入 HTTP 响应主体并由 REST 客户端轻松解析的规范错误类,即带有代码和消息。

    至于将异常转换为不同的 HTTP 响应,这取决于您使用的 Spring 和 REST 库的版本。有多种方法可以做到这一点,记录在 hereherehere

    您使用 RxJava 的事实在确定您的方法时并不重要。我使用了与您的示例类似的 onErrorResumeNext 代码。

    【讨论】:

      【解决方案2】:

      使用 RxJava 订阅机制来处理错误,使用onErrorResumeNext 来返回值而不是异常。我会这样做:

      //The web service call is just this
      private Single<Customer> findCustomerById(long customerId) {
              return Single.fromCallable(() ->
                          getRestTemplate().getForObject(MyBackendService.SEARCH_CUSTOMER_BY_ID.getUrl(),
                                  Customer.class,
                                  customerId));
          }
      ...
      
      //Then just manage the exception on the subscription
      findCustomerById(long customerId)
          .subscribe(customer -> {
              //Write the success logic here
              System.out.println(customer);
          }, throwable -> {
              //Manage the error, for example
              throwable.printStackTrace();
          });
      

      希望对你有帮助...

      【讨论】:

        猜你喜欢
        • 2023-03-04
        • 1970-01-01
        • 2021-07-10
        • 2013-07-02
        • 2022-10-19
        • 1970-01-01
        • 2016-07-11
        • 1970-01-01
        • 2014-12-16
        相关资源
        最近更新 更多