Home > Software engineering >  How to handle json API response errors in dart?
How to handle json API response errors in dart?

Time:01-05

I was trying to create a library to parse a few JSON http responses from an API so I made the request and created a model class and parsed the JSON response but sometimes (maybe if the user token expires), an exception with error 401 is returned, and since the error id is required to handle different errors I was thinking of creating another model class for the error and returning that to the user, but that would mean I'll have to either return the class with the required data or the class with the error information which is not possible to do with the same function at a time. Now, if I did a try-catch clause it wouldn't return anything if an exception occurs returning null (which I don't want).

The correct JSON response looks like the following:

{
  "result": "ok",
  "token": {
    "session": "string",
    "refresh": "string"
  }
}

and the error JSON response will look like the following:

{
  "result": "error",
  "errors": [
    {
      "id": "string",
      "status": 0,
      "title": "string",
      "detail": "string"
    }
  ]
}

Now, of course I could do an if else clause checking the response code and doing the rest but again I'll somehow have to return the error class with all the detail in it. How do I do so?

Note: I'm using the mangadex api

CodePudding user response:

I'd make a function that returns Future<Token>

If the result is okay, parse Token and return it.

If it's an error, throw a custom Error implementation with all of the details.

Then you create an idiomatic Dart API for your RPC.

  •  Tags:  
  • Related