使用Kotlin Coroutine遇无详细信息的致命异常求排查方案
Kotlin协程API请求崩溃排查思路
问题场景
我正在学习Kotlin Coroutines,尝试构建一个包含API请求的简单应用,但遇到了无详细信息的崩溃,日志仅显示:
FATAL EXCEPTION: main
Process: com.tests.myapp, PID: 14743
协程调用API的代码:
CoroutineScope(Dispatchers.Main).launch { API.call().registration(); }
使用的Kotlin Coroutines版本:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'
Retrofit相关代码:
object API { private const val BASE_URL = "http://my-test-url-comes-here.com" private val okHttpClient = OkHttpClient() .newBuilder() .addInterceptor(RequestInterceptor) .build() private fun getClient(): Retrofit = Retrofit.Builder() .client(okHttpClient) .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() fun call(): Endpoints { return getClient().create(Endpoints::class.java) } }
排查思路
补全协程异常捕获:当前代码未处理协程异常,导致日志缺失关键信息。添加异常处理器或用
try-catch包裹API调用,打印完整异常栈:val exceptionHandler = CoroutineExceptionHandler { _, throwable -> throwable.printStackTrace() } CoroutineScope(Dispatchers.Main + exceptionHandler).launch { try { API.call().registration() } catch (e: Exception) { e.printStackTrace() } }检查Retrofit接口定义:确认
Endpoints中的registration()方法是否标记为suspend挂起函数。Retrofit 2.6+支持协程,接口方法必须加suspend关键字,否则主线程调用会阻塞引发崩溃:interface Endpoints { @POST("registration") suspend fun registration(): Response<YourModel> }补充Android协程依赖:仅引入
coroutines-core不足以支持Android主线程调度,需添加对应Android依赖:implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'排查OkHttp拦截器:临时移除
RequestInterceptor,确认是否是拦截器内部逻辑(如空指针、非法参数)导致崩溃,逐步定位问题。验证BASE_URL格式:确保
BASE_URL以/结尾,不符合格式会触发Retrofit初始化异常。检查网络权限:确认AndroidManifest.xml中已添加网络权限,无权限会导致网络请求失败甚至崩溃:
<uses-permission android:name="android.permission.INTERNET" />
内容的提问来源于stack exchange,提问作者Adam Varhegyi
相关产品推荐
相关产品推荐

