question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to handle 4XX response

See original GitHub issue

Hi, thanks for great library. I have a question about handling 400 response.

I am developing an Android application on Kotlin and use rx_responseString() method to get a JSON from a Web API.

Api responses a JSON like bellow.

{
    "firstName": "hoge"
    "lastName" : "foo"
}

Data class for response.

data class User(val firstName: String, val lastName: String)

I want to get a User object from a api’s response with GSON.

// In a data access class
fun getUser(): Single<User> {

  // send a get request and convert response
  return "http://XXX/user".httpGet().rx_responseString()
    map {
      p ->
      val gson = Gson()
      gson.fromJson(p.second.get(), User::class.java)
    }
}

In an activity, I retrieve s result and display. When response status code is 4XX, I want to display error dialog with message.

// In an Activity
getUser().subscribeOn(Schedulers.newThread())
         .observeOn(AndroidSchedulers.mainThread())
         .subscribe(
         {
            // onSuccess
            res ->
              // display json to an Activity
         },
         {
            // onError
            e ->
              // check http status code
              when (httpStatusCode) {
                400 -> {
                     // show dialog with message
                }
                404 -> {
                    // show dialog with message
                } 
         }
         )

I want to know best practices to handle response with status code 4XX.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
keizo2commented, Oct 13, 2017

Thank you for replying! If I apply clean architecture like https://blog.uptech.team/clean-architecture-in-android-with-kotlin-rxjava-dagger-2-2fdc7441edfc, I guess it’s better to keep the return type of getUser method Single<User> and tried to return an error object in an exception as below. How is this?

// error object
data class ApiError(val errorCode: String, val message: String)
// the field contains an Api Error object.
class ApiException(val apiError: QiitaError) : Exception()
fun getUser(): Single<User> {

    return url.httpGet().rx_responseString().flatMap { p ->
        when (p.first.httpStatusCode) {
            200 -> {
                val gson = Gson()
                Single.create<User> { e ->
                    e.onSuccess(gson.fromJson(p.second.get(), User::class.java))
                }
            }
            400..419 -> {
                // handle an 4XX error 
                val input = InputStreamReader(ByteArrayInputStream(p.first.data))
                val gson = Gson()
                val error = gson.fromJson(input, ApiError::class.java)
                Single.error(QiitaException(error))
            }
            else -> {}
        }
    }
3reactions
babedevcommented, Oct 2, 2017

you can check statusCode in res object

getUser().subscribeOn(Schedulers.newThread())
         .observeOn(AndroidSchedulers.mainThread())
         .subscribe({ res ->
            val statusCode = res.first.statusCode
            when (statusCode) {
               400 -> { }
               401 -> { }
            }
         }, { e -> })

hope this answer your question 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to handle HTTP code 4xx responses in fetch api
The best approach I've found for this is to wrap it in a new Promise, and if response ...
Read more >
What is a 4XX Error? | 4XX HTTP Codes with Explanation
The first and most common method is to simply check the URL to make sure that you haven't made any spelling mistakes. In...
Read more >
How to deal with 4xx responses in MicroProfile Rest-Client
Tell the rest-client about the priority. · Our class needs to implement the ResponseExceptionMapper interface · We can retrieve the status code ...
Read more >
How to handle 4xx and 5xx errors in Javascript fetch()
To handle the 4xx and 5xx responses, the fetch API, fortunately, provides us with a flag ok in the response object.
Read more >
How to handle 4XX response · Issue #241 · kittinunf/fuel - GitHub
I have a question about handling 400 response. I am developing an Android application on Kotlin and use rx_responseString() method to get a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found