In order to handle statuscodes which are not 200
I used a StatusCodeHandler
which throws a extended Error
which I then can use in the catch
block of the returned promise.
class RequestError extends Error {
response: Response;
constructor(message: string, response: Response) {
super(message);
this.response = response;
this.message = message;
}
}
const StatusCodeHandler = (response: Response) => {
if (response.ok) return response;
const error = new RequestError(response.statusText, response);
throw error;
};
export default StatusCodeHandler;
Then I have my request method:
export default function someRestCall(somedata: string, someOtherdata: string) {
// code omitted
return fetch(someurl)
.then(StatusCodeHandler)
.then(respone => {
return respone;
}); // Do something with the error
}
And in the component I use it like this (here on a button):
<Button
title="Register"
onPress={() => {
someResCall(data1, data2)
.then(() => {
this.success();
})
.catch((err)=> {
Alert.alert('something went wrong');
this.noSuccess();
});
}}
/>
So far so good. However the requirements have changed and I get an error object back with informations which I have to handle in my component. But I have no idea how to get to this information in the catch block.
When I logerr.response
it does not contain this information.