Kotlin 协程异常全局捕捉

单个异常捕捉

  val handler = CoroutineExceptionHandler { coroutineContext, throwable ->
            Log.d(TAG, "onCreate: handler${throwable}")
        }
        Log.d(TAG, "onCreate:1")
        findViewById<Button>(R.id.button).also {
            it.setOnClickListener {
                GlobalScope.launch(handler) {
                    Log.d(TAG, "onCreate: onClick")
                    "anc".substring(10)
                }
            }
        }

launch里面如果不写handler

可以使用这样的方式来创建全局异常捕获处理

在main目录下

新建 resources\META-INF\services\kotlinx.coroutines.CoroutineExceptionHandler

 注意没有后缀哦

然后回到java类里面 随便找个位置创建class类

 内容

package com.example.coroutine

import android.util.Log
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlin.coroutines.CoroutineContext

class GlobalCoroutineExceptionHandler : CoroutineExceptionHandler {
    override val key = CoroutineExceptionHandler
    private  val TAG = "GlobalCortineExceptionH"
    override fun handleException(context: CoroutineContext, exception: Throwable) {
        Log.d(TAG, "handleException:${exception} ")
    }
}

根据包名和类目

package com.example.coroutine.
GlobalCoroutineExceptionHandler

我们可以确定这个文件的路径为

com.example.coroutine.GlobalCoroutineExceptionHandler

写到刚才创建的没有后缀的文件当中去

程序里删除 hander

      findViewById<Button>(R.id.button).also {
            it.setOnClickListener {
                GlobalScope.launch {
                    Log.d(TAG, "onCreate: onClick")
                    "anc".substring(10)
                }
            }
        }

点击按钮后程序会闪退

但是

 异常可以拿到。这就很好了

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/126458290
今日推荐