RxDart Handle API call for each error code response

50 views Asked by At

I am trying to make an API call using RxDart and I want to handle all HTTP error codes(5xx,4xx) in my code. I am trying the below approach but I am not sure where to put my code to parse the response correctly.

RxDart version: 0.27.7

My current approach is working fine with 200 code but I want to handle 4xx, and 5xx separately in the same chain if possible.

http
    .get("http://www.api.com/api/?q=$text")  
    .then((response) => response.body)
    .then(JSON.decode)
    .then((map) => map["results"])
    .then((list) {
  list.forEach(_addItem); 
})
    .catchError(_onError)
    .then((e) {
  setState(() {
    _isLoading = false;
  });
});
1

There are 1 answers

0
Naman R. On

Please Use Below code for handle 5xx and 4xx status code

http
.get("http://www.api.com/api/?q=$text")  
.then((response) {
    if (response.statusCode == 200) {
        return response.body;
    } else if (response.statusCode >= 400 && response.statusCode < 500) {
        // your code for handle error
    } else if (response.statusCode >= 500 && response.statusCode < 600) {
         // your code for handle error
    } else {
        throw Exception("Unexpected Error: ${response.statusCode}");
    }
})
.then(JSON.decode)
.then((map) => map["results"])
.then((list) {
    list.forEach(_addItem); 
})
.catchError((error) {
    
})
.then((_) {
    setState(() {
        _isLoading = false;
    });
});