はじめに
今回は、HttpExceptionのの中からエラー内容を取り出すための処理を紹介します
本文
fun Throwable.getDisplayMessage(): String? {
if (this !is HttpException) return null
return try {
val jsonBody = this.response()?.errorBody()?.string() ?: return null
val errorEntity = Serializer.kotlinxSerializationJson.decodeFromString<ErrorUnprocessableEntityEntity>(jsonBody)
errorEntity.displayMessage
} catch (e: Exception) {
Timber.w(e, "Failed to parse error response for display_message")
null
}
}
最後に
エラーの詳細を表示することでユーザーが何を改善すればいいのかを明瞭化するのに、頻出すると思うので記事にしました