2017-07-31 46 views
0

我想知道什么是与RxJava和春季REST API最好?RxJava自定义异常处理/传播在春季启动休息应用程序

我有一个简单的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); 
} 

所以,问题是如何映射/与传播RxJavaBackendException让我们说NotFound(404 )或InternalServerError(500)?

回答

0

我已经使用了异常库,它们对于每种类型的HTTP响应都有例外,它们可以放入HTTP响应的主体中,并且可以通过REST客户端轻松解析,也就是说,一个代码和一条消息。

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

您使用RxJava的事实在确定您的方法时并不重要。我已经使用了类似的onErrorResumeNext代码来表达你在例子中的内容。

0

使用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(); 
    }); 

希望它可以帮助...