這是我的 RemoteDataSource 類,我將在其中撰寫許多這樣的 api 呼叫:
suspend fun getReviewData1() = getResult {
try {
apiService.getReviewData(getCustomerId())
} catch (e: Exception) {
handleException(e)
}
}
suspend fun getReviewData2() = getResult {
try {
apiService.getReviewData(getCustomerId())
} catch (e: Exception) {
handleException(e)
}
}
現在,您可以看到,對于每一個樂趣,我都需要將我的代碼包裝在 try/catch 塊中。一切正常,我也可以捕獲例外,但是為什么要為每個函式撰寫這么多的 try/catch 呢?相反,我需要在一個公共類中做,這樣我就可以像這樣簡單地呼叫我的函式 SOMETHING。
suspend fun getReviewData() = getResult {
apiService.getReviewData(getCustomerId())
}
如果您想進行任何更改,您可以寫一個答案并建議我,例如 getResult()
getResult() 在另一個基類中:
protected suspend fun <T> getResult(call: suspend () -> Response<T>?): Resource<T> {
try {
val response = call()
if (response?.isSuccessful == true) {
val body = response.body()
if (body != null) return Resource.success(body, response.message(), response.code())
}
return error((response?.message() ?: context.getString(R.string.unable_to_reach_server)),
(response?.code() ?: AppConstants.INetworkValues.DEFAULT_ERROR_CODE))
} catch (e: Exception) {
return error(e.message ?: e.toString(), (call()?.code() ?: AppConstants.INetworkValues.DEFAULT_ERROR_CODE))
}
}
private fun <T> error(message: String, code: Int): Resource<T> {
LogUtils.d(message)
return Resource.error(null, message, code)
}
處理例外()
fun handleException(e: Exception): Response<Any> {
if (e is NoConnectivityException) {
return Response.error(AppConstants.INetworkValues.INTERNET_ERROR_CODE, getDummyResponseBody())
} else {
return Response.error(AppConstants.INetworkValues.DEFAULT_ERROR_CODE, getDummyResponseBody())
}
}
我試過這個答案,但它只是沒有發生: https ://stackoverflow.com/a/46517243/14016240
請幫忙。
uj5u.com熱心網友回復:
您的getResult函式在 catch 塊中有錯誤。call()如果第一次呼叫call()引發例外,您將再次呼叫。我認為再次呼叫它沒有意義,因為它可能會再次拋出并且您將無法回傳您的Resource.error.
如果你解決了這個問題,你就不需要在你的其他函式中使用 try/catch 了,因為call它會被安全地包裹起來try/catch并將任何錯誤打包到一個Resource.error.
修復它:由于您已經response?.code在 try 塊中處理,沒有理由重復進入call()?.codecatch 塊。您可以將其簡化為
return error(e.message ?: e.toString(), AppConstants.INetworkValues.DEFAULT_ERROR_CODE)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/443402.html
上一篇:似乎將browsermob-core添加到我的依賴項會導致我的seleniumwebdriver停止作業
下一篇:移動專案后訪問R資源時出錯
