2017-07-31 44 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(); 
    }); 

希望它可以幫助...