【问题标题】:Why I get Unable to create converter exception from retrofit?为什么我无法从改造中创建转换器异常?
【发布时间】:2021-06-28 06:37:37
【问题描述】:

我的问题是,当我在我的改造 api 中使用 Call 时,我得到了这个异常:

无法为 retrofit2.Call 创建转换器 对于方法 IntegApi.getAllProductBarcodeAsync

有趣的是,如果我不使用 Call,那么错误消息就消失了。

我想使用Call,因为我想使用自定义响应类,因为我想知道api何时发送404状态,然后我想跳过这个异常。

我使用 Moshi 转换 Json

Sync function: 
    private suspend fun syncProductBarcodes() {
        try {
            val productBarcodes = api.getAllProductBarcodeAsync().await()
            
            if(productBarcodes.isSuccessful) {
                productBarcodeRepository.deleteAndInsertAll(productBarcodes.body() ?: emptyList())
                addOneToStep()
            }
        }catch (e: Exception){
            Timber.d(e)
            throw e
        }
    }

Api: 
    @GET("Product/GetAllBarcode")
    suspend fun getAllProductBarcodeAsync(): Call<List<ProductBarcode>>

Entity class: 
@Entity(
    tableName = ProductBarcode.TABLE_NAME
)
@JsonClass(generateAdapter = true)
class ProductBarcode(
    @PrimaryKey
    @ColumnInfo(name = "id")
    @Json(name = "Id")
    val id: String = "",
    @ColumnInfo(name = "product_id", index = true)
    @Json(name = "ProductId")
    var ProductId: String = "",
    @ColumnInfo(name = "barcode", index = true)
    @Json(name = "Barcode")
    var barcode: String = ""
) {
    companion object {

        const val TABLE_NAME = "product_barcode"
    }
}

ExtensionFun: 
suspend fun <T> Call<T>.await(): Response<T> = suspendCoroutine { continuation ->
    val callback = object : Callback<T> {
        override fun onFailure(call: Call<T>, t: Throwable) {
            continuation.resumeWithException(t)
        }

        override fun onResponse(call: Call<T>, response: Response<T>) =
            continuation.resumeNormallyOrWithException {
                if (response.isSuccessful || response.code() == 404) {
                    return@resumeNormallyOrWithException response
                } else {
                    throw IllegalStateException("Http error ${response.code()}, request:${request().url()}")
                }
            }
    }
    enqueue(callback)
}

ApiModule:
    @Provides
    @Singleton
    fun provideMoshi(): Moshi {
        return Moshi.Builder()
            .add(DateConverter())
            .add(BigDecimalConverer())
            .add(KotlinJsonAdapterFactory())
            .build()
    }

fun provideIntegApi(
        @Named("base_url") url: String, moshi: Moshi,
        prefManager: PrefManager
    ): IntegApi {

        var builder = OkHttpClient.Builder()
        builder = BuildTypeInitializations.setupInterceptor(builder)

        builder.addInterceptor { chain ->
            val request = chain.request().newBuilder()
                .addHeader("Authorization", "Bearer ${prefManager.token}")
                .addHeader("Connection", "close")
                .build()

            val response = chain.proceed(request)

            return@addInterceptor response
        }
            .readTimeout(5, TimeUnit.MINUTES)
            .writeTimeout(5, TimeUnit.MINUTES)
            .connectTimeout(5, TimeUnit.MINUTES)
            .retryOnConnectionFailure(true)

        return Retrofit.Builder()
            .baseUrl(url)
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .client(builder.build())
            .build()
            .create(IntegApi::class.java)
    }

我不知道为什么,但是如果 Api 发送 404 响应,之后我得到 Unable to crate converter 异常,但是我服务器发送响应,错误消息消失了。

更新:

如果是使用这个:

    @get:GET("Product/GetAllBarcode")
    val getAllProductBarcodeAsync: Call<List<ProductBarcode>>

而不是这个:

   @GET("Product/GetAllBarcode")
    suspend fun getAllProductBarcodeAsync(): Call<List<ProductBarcode>>

不会出错,一切正常,但我不明白是什么问题

更新2 我把Moshi改成Jackson,并没有像moshi那样抛出转换器错误,而是抛出对我来说更友好的Http 404错误,但我并不完全满意。因为 Http 404 错误,我创建了 await() fun,我认为这一堆代码是因为 http 404 而跳过的?

【问题讨论】:

  • 您可以尝试将您的呼叫扩展功能签名更改为内联乐趣...
  • 我认为这不会有帮助,因为我得到了同样的错误,如果我使用内置 await() 方法的改造
  • 泛型类型仅在编译期间可用,因为编译器将使用它们各自的实际值更改泛型。因此,在运行时,转换器没有 T 值可以达到,并且使用 reified 关键字可以使泛型在运行时可用。我想这就是无法创建转换器的原因。
  • 我改变了乐趣,但我得到了同样的错误更新乐趣:suspend inline fun &lt;reified T&gt; Call&lt;T&gt;.await(): Response&lt;T&gt; = suspendCoroutine { continuation -&gt;

标签: android kotlin retrofit


【解决方案1】:

最后我发现了问题,我犯了一个错误,因为我尝试同时使用suspend fun和retrofit Call。我删除了suspend关键字,效果很好。

【讨论】:

    猜你喜欢
    • 2016-06-23
    • 2021-05-13
    • 2018-10-19
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多