6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Retrofit2のerrorBodyから値を利用する時の注意

Last updated at Posted at 2018-07-23

#概要
APIでErrorで返された時に、errorBodyの中の情報を用いて挙動を変える必要があった時の備忘録

##環境
Kotlin
Retrofit2
Rxjava2
okhttp3
Gson
CompositeDisposable
を利用

##注意点
###・ResponseのオブジェクトをResponseで囲む

ApiService.kt
    @Get("/hoge")
    fun getHoge(): Single<HogeResponse>
HogeActivity.kt
ompositeDisposable.add(hogeViewModel.getHogeData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ //it:HogeResponse
                    
                }, {//it:Throwable!
                    
                }))

okHttp3のIntercepterを利用したりすればどうにかできるかもしれないけど、これだとerrorBodyが得られなかったので以下のようにした

ApiService.kt
    @Get("/hoge")
    fun getHoge(): Single<Response<HogeResponse>>
HogeActivity.kt
ompositeDisposable.add(hogeViewModel.getHogeData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ //it:Response<HogeResponse>
                   if (it.isSuccessful) {
                   } else {
                       val errorResponse = Gson().fromJson<ErrorResponse>(it.errorBoey()?.toString(), ErrorResponse::class.java) 
                   }
                }, {//it:Throwable!
                    
                }))

errorBodyは取得できたが、jsonをパースするのに失敗
###・errorBody?.toString → errorBody?.string()

jsonのStringを得るにはtoStringじゃなくてstring()だったというだけの話
errorBody?.toString() =>"okhttp3.ResponseBody$1@f0875b5"
errorBody?.string() => {"error":{"message":"Not Found", "error":{"status":404}}}

HogeActivity.kt
ompositeDisposable.add(hogeViewModel.getHogeData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ //it:Response<HogeResponse>
                   if (it.isSuccessful) {
                       
                   } else {
                     val errorResponse = Gson().fromJson<ErrorResponse>(it.errorBody()?.string(), ErrorResponse::class.java) 
                   }
                }, {//it:Throwable!
                    
                }))
ErrorResponse.kt
data class ErrorResponse(
    @SerializedName("message")
    var message: String,

    @SerializedName("error")
    var error: Error
)

API関連はライブラリに頼りっぱなしになっていたので、いま一度詳細を確認しておきたいと思ってから時間ばかりがすぎる今日この頃...orz

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?