Error Handling in HTTP Ajax Call using $fetch Javascript - javascript

I tried to handle the Network related issues in HTTP ajax call. So, I temporarily stopped the respective API's service in IIS and I tried to call the shut downed API - http://localhost:1000/GetData.
fetch("http://localhost:1000/GetData")
.then(handleErrors)
.then(function(response) {
return response.Json();
}).catch(function(error) {
console.log(error);
});
I tried the following code too
fetch("http://localhost:1000/GetData")
.then(response => {
if(response) {
if (response.status === 200) {
alert('Super');
return response.json();
} else {
alert('Hai');
return '';
}
} else {
alert('Oooops');
return '';
}
})
.catch(function(error) {
console.log(error);
});
But its failing and directly hitting the catch block without triggering any alert and its throwing an error. Moreover the response.json(); is in Success block, I don't know how its executed.
TypeError: response.json is not a function
Stack trace:
onFetchError/<#http://192.168.4.159:3000/app.0df2d27323cbbeada2cd.js:9946:13
Kindly assist me how to check the Status code and how to handle the Network error (i.e., Network Unavailable 404, etc.,)
Referred website: https://www.tjvantoll.com/2015/09/13/fetch-and-errors/

Based on this issue on Github, you can try to identify error types in catch block instead. So, something like this may work for your case:
fetch("http://localhost:1000/GetData")
.then(response => {
alert("Super");
return response.json();
})
.catch(err => {
const errStatus = err.response ? err.response.status : 500;
if (errStatus === 404){
// do something
} else {
// do another thing
}
});

Related

Axios override, get status code from the data response instead of status

I'm calling an API that defines the statusCode from data instead of the response code:
{
data: {
statusCode: 422,
message: "User's not found"
},
status: 200
}
In my axios get request it's getting the status code from the status instead in data.
return axios.get(`${process.env.BASE_URL}/users`)
.then(response => {
console.log(response);
}).catch(err => {
console.log(err.message);
});
I'm getting the response but it should go to catch since it's 422.
How can I refer to the statusCode of the data response so that if it's not 200 it should go to catch statement
You can intercept the response, inspect the data and throw a custom error in this case:
// Add a response interceptor
axios.interceptors.response.use(function(response) {
if (response.data && response.data.statusCode && !(response.data.statusCode >= 200 && response.data.statusCode < 300)) throw new Error()
return response;
}, function(error) {
return Promise.reject(error);
});
// Make a GET request
axios.get(url)
.then((data) => {
console.log('data', data)
})
.catch((e) => {
console.log('error', e)
})
This way you configure your axios instance so you dont have to repeat yourself for every single request in your app
Also, you can override the status using following code. But since status validation has already executed, it will not throw errors on bad status codes
// Add a response interceptor
axios.interceptors.response.use(function(response) {
if (response.data && response.data.statusCode) response.status = response.data.statusCode
return response;
}, function(error) {
return Promise.reject(error);
});
You can handle with standard if statement inside the .then()
return axios.get(`${process.env.BASE_URL}/users`)
.then(response => {
if(response.data.statusCode===442){
...//custom error handling goes here
}else{
...//if statusCode is a success one
}
}).catch(err => {
console.log(err.message);
});
Check the response.data.statusCode value, if it is 442 then you should ideally throw an Error and let it be handled in the .catch callback.
return axios.get(`${process.env.BASE_URL}/users`)
.then(response => {
if(response.data.statusCode===442){
throw new Error(response.data.message); //using throw instead of Promise.reject() to break the control flow.
}else{
//return the data wrapped in promise
}
})
.catch((err) => {
console.log(err.message);
return Promise.reject(err.message);
});

Axios - Prevent .then() from executing on http errors

My problem:
I have set up an interceptor to catch error codes in HTTP responses.
When the JWT expires, I have a code 401 coming back from the server. Here's my interceptor:
this.axios.interceptors.response.use(undefined, (error) => {
if (error.response.status === 401) {
this.$store.dispatch('auth/logout').then(() => {
this.$router.push({name: 'login'})
return Promise.reject(error)
})
}
})
My interceptor works fine, except the request that is being intercepted still resolves into the .then() part.
this.axios.get('/texts').then(function(){
// This is still being executed and generates javascript errors because the response doesn't contain the right data
})
From the axios documentation, I found out you can prevent this by calling
this.axios.get('/texts').then(function(){
// only on success
}).catch(function(){
// only on errors
}).then(function(){
// always executed
})
But this is pretty verbose and I don't want to do this on every request that my app makes.
My question is:
How do I prevent axios from executing the .then() callback when I have an error. Is it something I can do in the interceptor? Like event.stopPropagation() or something like that?
You can prevent the Axios Error by using the below set of code
this.axios.interceptors.response.use(undefined, (error) => {
if (error.response.status === 401) {
this.$store.dispatch('auth/logout').then(() => {
this.$router.push({name: 'login'})
return new Promise(() => { });
})
} else {
return Promise.reject(error)
}
})
Throw an exception from catch block to prevent 'then' block
this.axios.get('/texts').then(function(){
// only on success
}).catch(function(e){
// only on errors
throw e;
}).then(function(){
// Will not executed if there is an error but yes on success
})
Did you try catch in the end of the chain? You will get following
this.axios.get('/texts').then(function(){
// only on success
}).then(function(){
// only on success in previous then
}).catch(function(){
// executes on every error from `get` and from two previous `then`
})

nested fetch for a response in a service-worker

I'm new to service-worker. I'm following a training of Mobile Web Specialist given by Udacity and I'm using google-chrome for that.
I want to fetch for a response from the network, and if it returns 404 as a status I fetch for another response from the network as well.
This is a code to fetch from the network only once. This code works perfectly:
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).then(function(response) {
if (response.status === 404) {
return new Response("Whoops, not found");
}
return response;
}).catch(function() {
return new Response("Uh oh, that totally failed!");
})
);
});
I did some updates on this code by throwing an error after getting response.status === 404 and manage it the same way in a try/catch. The updated code is below:
self.addEventListener('fetch', function(event) {
try {
event.respondWith(
fetch(event.request).then(function(response) {
if (response.status === 404) {
throw (Error);
}
return response;
}).catch(function() {
return new Response("Uh oh, that totally failed!");
})
);
} catch (Error) {
event.respondWith(
fetch('/imgs/dr-evil.gif').then(function(response) {
if (response.status === 404) {
return new Response('couldn\'t fetch twice');
}
return response;
}).catch(function() {
return new Response("Uh oh, that totally failed twice!");
})
);
}
});
I know there is a better way to do a nested fetch using the service-worker, but I want to know what I did wrong here.
I've not run this so it's possible it needs some adjustments, but try something like this. The problem with your current code is that the first fetch promise chain always resolves to a Response. Either in the first then or in the first catch, where you return a response of "Uh oh, that totally failed!". The event.respondWith takes that response and happily goes along it's way.
The outer try/catch exists in a synchronous space, where as the fetch kicks off an asynchronous chain, so there will be no way for your code to reach the outer catch since it's not in the execution context for the fetch.
If the compatability is the same for both service worker and async/await (I don't know) you might want to take a look at that as it would be a much friendlier way to structure your code.
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).then(function(response) {
if (response.status === 404) {
throw (Error);
}
return response;
}).catch(function() {
return fetch('/imgs/dr-evil.gif').then(function(response) {
if (response.status === 404) {
throw (Error);
}
return response;
})
}).catch(function() {
return new Response("Uh oh, that totally failed twice!");
})
);
});

Axios HTTP call is always treated as succeed

So I'm trying for multiple ways to get error response status from my axios HTTP call and something weird is happening.
getData() {
axios.get(`/api/article/getObserved.php`, axiosConfig)
.then(response => {
console.log('success');
console.log(response);
})
.catch(err => {
console.log('error');
console.log(err.status);
console.log(err.response.status)
});
}
So I'm calling my getObserved endpoint and although it's returning http_response_code(503); it's going to .then() part because it console log 'success' string.
this is output from console:
GET http://localhost/obiezaca/v2/api/article/getObserved.php 503 (Service Unavailable)
success favouriteArticles.vue?31bd:83
I've done hundreds of calls like this and this .catch was always catching error even tho I'm not throwing exception like in other lenguages I would do. However I also tried like this:
getData() {
axios.get(`/api/article/getObserved.php`, axiosConfig)
.then(response => {
console.log('success');
console.log(response);
}, function (err) {
console.log('error');
console.log(err.status);
console.log(err.response.status);
})
.catch(err => {
console.log('error');
console.log(err.status);
console.log(err.response.status)
});
}
But it still doesn't console 'error' although I have this 503 bad request returned from my endpoint. Why?
I also would like to add that I dont think my endpoint is not working correctly because I was testing it with tests and manually by cURL and POSTMAN and everything was fine.
Edit since response is undefined when I don't get data from my endpoint and I need to handle only one error (there is data or not) I have just do something like this:
getData() {
axios.get(`/api/article/getObserved.php`, axiosConfig)
.then(response => {
if(response) {
this.articles = response.data.records;
} else {
this.noFavourite = true;
this.articles = [];
}
});
and it's working. I'll pray to not get into same issue with some call where I'll need to handle several different errors.
This issue was related to my httpInterceptor
import axios from 'axios';
import { store } from '../store/store';
export default function execute() {
axios.interceptors.request.use(function(config) {
const token = store.state.token;
if(token) {
config.headers.Authorization = `Bearer ${token}`;
//console.log(config);
return config;
} else {
return config;
}
}, function(err) {
return Promise.reject(err);
});
axios.interceptors.response.use((response) => {
return response;
}, (err) => {
console.log(err.response.status)
return Promise.reject(err); // i didn't have this line before
});
}
which wasn't returning promise on error response so after in promise of http call it somehow treated it as success. After adding return Promise.reject(err); inside my interceptor it's working fine

react native fetch not calling then or catch

I am using fetch to make some API calls in react-native, sometimes randomly the fetch does not fire requests to server and my then or except blocks are not called. This happens randomly, I think there might be a race condition or something similar. After failing requests once like this, the requests to same API never get fired till I reload the app. Any ideas how to trace reason behind this. The code I used is below.
const host = liveBaseHost;
const url = `${host}${route}?observer_id=${user._id}`;
let options = Object.assign({
method: verb
}, params
? {
body: JSON.stringify(params)
}
: null);
options.headers = NimbusApi.headers(user)
return fetch(url, options).then(resp => {
let json = resp.json();
if (resp.ok) {
return json
}
return json.then(err => {
throw err
});
}).then(json => json);
Fetch might be throwing an error and you have not added the catch block. Try this:
return fetch(url, options)
.then((resp) => {
if (resp.ok) {
return resp.json()
.then((responseData) => {
return responseData;
});
}
return resp.json()
.then((error) => {
return Promise.reject(error);
});
})
.catch(err => {/* catch the error here */});
Remember that Promises usually have this format:
promise(params)
.then(resp => { /* This callback is called is promise is resolved */ },
cause => {/* This callback is called if primise is rejected */})
.catch(error => { /* This callback is called if an unmanaged error is thrown */ });
I'm using it in this way because I faced the same problem before.
Let me know if it helps to you.
Wrap your fetch in a try-catch:
let res;
try {
res = fetch();
} catch(err) {
console.error('err.message:', err.message);
}
If you are seeing "network failure error" it is either CORS or the really funny one, but it got me in the past, check that you are not in Airplane Mode.
I got stuck into this too, api call is neither going into then nor into catch. Make sure your phone and development code is connected to same Internet network, That worked out for me.

Categories