-1

I am using Retrofit 2.6.3 .

I can directly return data model now with Retrofit:

interface WikiApiService {

    // Here declare that the function returns Observable<Student>
    @GET("student/")
    fun getStudent(@Query("id") sid: Int): Observable<Student>

    companion object {
        fun create(): StudentApiService {

            val retrofit = Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl("https://foo.bar.com/")
                    .build()

            return retrofit.create(StudentApiService::class.java)
        }
    }
}

Then I can call above fun getStudent(@Query("id") sid: Int): Observable<Student> in UI layer to get an observable data.

All works fine to me & this is concise code, but now I get confused, how can I do response error handling now? Could someone please guide me?

Leem
  • 17,220
  • 36
  • 109
  • 159

1 Answers1

0

Like this:

    getStudent(1)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subsribe({ result ->
            // Success
        }, { error ->
            // Log the error here using your log mechanism

            // Switch on type and perform relevant actions
            when (error) {
                is HttpException -> {
                    // Based on the code, perform relevant action
                    when (error.code) {
                        404 -> // Handle not found
                        500 -> // Handle internal server error
                        else -> // Handle generic code here
                    }
                }
                else -> {
                    // Handle non http exception here
                }
            }
        })

In other words, you need to subscribe to the result in order for the API call to actually be made. You'll want to subscribeOn Schedulers.io to make sure the API call runs on a background thread, and then observeOn AndroidSchedulers.mainThread to make sure the response is delivered to the main thread.

If an error occurs during the API call, the error lambda will be invoked and it is here where you will do your error specific logic (i.e. checking if an HttpException occurred and, if so, performing relevant actions).

Thomas Cook
  • 4,371
  • 2
  • 25
  • 42