首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用kotlin协程处理2.6中的无互联网连接错误

使用kotlin协程处理2.6中的无互联网连接错误
EN

Stack Overflow用户
提问于 2019-06-22 15:24:17
回答 3查看 10.2K关注 0票数 4

我正在使用升级2.6和kotlin协程来进行API调用而不阻塞UI线程,我让它工作了,但当我关闭互联网连接时,应用程序崩溃了。logcat错误为: E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1

下面是我的代码:

代码语言:javascript
复制
private fun handleIntent(slug: String) {
    val service = UtilityMethods.migrationTimeService()

    UtilityMethods.showView(loading_view)
    UtilityMethods.hideView(network_error_msg)

    CoroutineScope(Dispatchers.IO).launch {
        val res = service.getPostBySlug(slug)

            try {
                withContext(Dispatchers.Main) {

                    //Do something with response e.g show to the UI.
                    val post = res.body()!!.first()

                    UtilityMethods.hideView(loading_view)

                    val title = post.title?.rendered
                    val content = post.content?.rendered
                    val imageUrl = post.jetPackFeaturedMediaUrl

                    title_txtView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        Html.fromHtml(title, Html.FROM_HTML_MODE_COMPACT).toString()
                    else
                        Html.fromHtml(title).toString()

                    content_txtView.loadData(content.toString(), "text/html", "UTF-8")

                    Picasso.get().load(imageUrl).fit().centerCrop().into(thumbnail_imgview)
                }

            } catch (e: HttpException) {
                UtilityMethods.showView(network_error_msg)
            } catch (e: Throwable) {
                Toast.makeText(this@PostContentActivity, "Ooops: Something else went wrong", Toast.LENGTH_LONG)
            }
    }
}
EN

回答 3

Stack Overflow用户

发布于 2019-06-23 18:07:37

我已经让代码工作了,新的代码是:

代码语言:javascript
复制
private fun handleIntent(slug: String) = GlobalScope.launch(Dispatchers.Main) {
    val service = UtilityMethods.migrationTimeService()

    UtilityMethods.showView(loading_view)
    UtilityMethods.hideView(network_error_msg)

    try {
        val res = withContext(Dispatchers.IO) {
            service.getPostBySlug(slug)
        }

        //Do something with response e.g show to the UI.
        val post = res.body()!!.first()

        UtilityMethods.hideView(loading_view)

        val title = post.title?.rendered
        val content = post.content?.rendered
        val imageUrl = post.jetPackFeaturedMediaUrl

        title_txtView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            Html.fromHtml(title, Html.FROM_HTML_MODE_COMPACT).toString()
        else
            Html.fromHtml(title).toString()

        content_txtView.loadData(content.toString(), "text/html", "UTF-8")

        Picasso.get().load(imageUrl).fit().centerCrop().into(thumbnail_imgview)
    }
    catch (e: HttpException) {
        Toast.makeText(this@PostContentActivity, "Exception ${e.message}", Toast.LENGTH_LONG).show()
    }catch (e: IOException) {
        UtilityMethods.hideView(loading_view)
        UtilityMethods.showView(network_error_msg)
    } catch (e: Throwable) {
        Toast.makeText(this@PostContentActivity, "Ooops: Something else went wrong ${e.message}", Toast.LENGTH_LONG).show()
    }
}
票数 4
EN

Stack Overflow用户

发布于 2019-11-02 18:28:45

因此,在查看堆栈跟踪时,我发现当网络不可用时会抛出ConnectException

这就是我在kotlin中的做法,对我来说很管用,

代码语言:javascript
复制
suspend fun<T: Any> safeAPICall(call: suspend () -> Response<T>) : T{
val response = try {
    call.invoke()
}
catch (e:java.lang.Exception){
    e.printStackTrace()
    val message = if( e is ConnectException) "Connection Error" else "Something went wrong. Please try again."
    throw IOException(ResponseError(message, 500).convertToJsonString())
}


// When connection is OK

if(response.isSuccessful){
    return response.body()!!
}else{
    val error = response.errorBody()?.string()

    error?.let{
        val message = JSONObject(it).optString("message", "Something went wrong")
        val responseError = ResponseError(message, response.code())
        throw IOException(responseError.convertToJsonString())

    }
    throw IOException(ResponseError("Something went wrong. Please try again.", 500).convertToJsonString())
}
}

我使用的数据类

代码语言:javascript
复制
data class ResponseError(val message:String, val errorCode:Int)

用法:

代码语言:javascript
复制
try {
      val response = safeAPICall {APIClient.planner.viewSites(view.context.authToken)}
 }
 catch (e:Exception){
    view.snack(e.message?.toModel<ResponseError>()?.message?: unspecified_error)
 }

奖励:

代码语言:javascript
复制
 inline fun <reified T> JSONObject.toModel(): T? = this.run {
   try {
       Gson().fromJson<T>(this.toString(), T::class.java)
   }
   catch (e:java.lang.Exception){ e.printStackTrace(); null }
}


inline fun <reified T> String.toModel(): T? = this.run {
   try {
      JSONObject(this).toModel<T>()
    }
   catch (e:java.lang.Exception){  null }
}
票数 2
EN

Stack Overflow用户

发布于 2019-06-22 16:58:59

而不是这样:

代码语言:javascript
复制
    CoroutineScope(Dispatchers.IO).launch {
    val res = service.getPostBySlug(slug)

        try {
            withContext(Dispatchers.Main) {

试试这个:

代码语言:javascript
复制
    CoroutineScope(Dispatchers.Main).launch {
    val res = service.getPostBySlug(slug)

        withContext(Dispatchers.IO) {
            try {

将“try and catch”块代码包装在Dispatchers.IO中,而不是将Dispatchers.IO包装在try块中

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56713483

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档