getting result data + Error handling in Fetch - javascript

I've been looking for this over and over but cant find the proper answer
Using Fetch, in order to throw errors when getting status other than ok we must do it manually.
The back end is providing with an specific message about the error along the 401,404 etc, error code.
I want to access to it on my fetch but dont know how.
.then((response) => {
if (response.ok) {
return response.text();
}
else {
throw new Error(response.text()); ///THIS DOES NOT WORK.
}
})
.then(result => alert ("Added Successfully"))
.catch(error =>alert (error.message)); ///AND OF COURSE NEITHER DOES THIS.

You should console log your response and see what it contains. You also have to access the response object like this: response.text. You access it like its a function. You probably also have to parse the response before you access anything. Even though you didnt post the content of the response, the following snippet should point you into the right direction.
Check the snippet below which shows you a successfull error handling.
fetch("http://httpstat.us/404")
.then( response => {
if (!response.ok) {
throw new Error(response)
}
return response.json()
})
.catch( err => {
console.log(err.message);
})

Related

Why are my forced GET errors occurring twice instead of once in the browser?

Is this expected? I am testing the error checking of my code by forcing a GET error. That is, I turned off the endpoints on purpose. Oddly I am getting two errors for each single error.
I verified my fetch() request only occurs once by logging it to the console.
However I see two errors in the console. I wanted to make sure that for some reason the browser is not fetching the data twice.
Is this expected behavior? If so where is it documented?
GET http://localhost:3000/users/user 404 (Not Found)
It occurs twice for a single fetch();
Here is the fetch()
const options = {
credentials: 'include'
};
fetch('/users/user', options)
.then((response) => {
return response.json();
})
.then((user) => {
if(user) {
dispatch({type: 'initializeUser', current: user});
}
})
.catch((err) => {
console.error('DEBUG: F1Data: /users/user endpoint failed : ', err);
})
Similarly, I see my own error being thrown twice as well:
DEBUG: F1Data: /users/user endpoint failed : SyntaxError: Unexpected token < in JSON at position 0

Error handling in fetch: How do prevent .then from being called after .catch in slow network?

I've encountered a unexpected behavior in my fetch code when the internet connection is slow.
Consider the following code (not my actual code):
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
fetch("http://url")
.then(handleErrors)
.then(response => console.log("success") )
.catch(error => console.log("error") );
// "error"
// "success" (why is this called?)
The only way I can explain this behaviour is that the response is somewhat of an async function itself (check out https://stackoverflow.com/a/33446005/3016745). Meaning that first the request is sent, immediately after the connection times out and throws an error, and last the response is coming and calls the .then.
I checked the backend and the request and response both were successful.
Does this make sense? How do I prevent this behaviour?

Save JSON in Local Storage after the fetch

Sorry if this was posted a lot, I read through several articles but could not find the solution. So, I'm fetching a large JSON from this API, and I would like to cache the response somehow in the localStorage, so the next time the page loads, the scripts first checks if there is an object with the requested ID inside the JSON, and renders the content if there is one - and if there isn't, goes of to the API to fetch it.
I was thinking of setting up two fetch() functions, and this is what I have:
fetch(url + id)
.then((response) => {
localStorage.setItem('myResponse', response);
})
.catch((error) => {
console.log(error);
})
Then, check if there is something saved inside the localStorage, and if it is good, use it to render the HTML, if not, go on to another fetch to get it from the API.
if(localStorage) {
createHTML(localStorage.myResponse);
} else {
fetch(url + id)
.then(response => response.json())
.then(data => createHTML(data))
}
But, in the first fetch, if I use JSON.stringify(response), it just shows it as an empty object, so it the localStorage it looks like: myResponse - {}. If I do console.log(response.json()); on the first fetch, it shows Promise {<pending>}.
I've tried to make something out of that, but without results...any help much appreciated!
response.json() is a Promise, it needs to be either awaited, or chained a .then(); If you simply log it as is, all you'll get is Promise {<pending>} because it hasn't resolved yet.
fetch(url + id)
.then( response => response.json() )
.then( json => {
localStorage.setItem('myResponse', JSON.stringify(json));
})
Or with the async/await syntax :
const response = await fetch(url + id);
const json = await response.json();
localStorage.setItem('myResponse', JSON.stringify(json));

Fetch API: Handling a bad URL

I want to bullet-proof some code which takes user input and attempts to fetch data from a URL.
I have something like the following:
fetch(url)
.then(response=>{
console.log(response.ok);
response.text();
})
.catch(error=>console.log(error));
There’s more afterwards in the actual code.
If I enter something like http://rubbish I catch a TypeError which I can handle. If I enter something like rubbish (without the http:// protocol), I get an error like :
GET file:///…/rubbish net::ERR_FILE_NOT_FOUND
and then get my TypeError. The actual error occurs on the first line of the code above, before the catch() block.
What is the correct way to handle an error like this?
I’m doing this in an Electron App, so one thing I don’t have to worry about is browser compatibility.
You could potentially execute different logic in the catch block depending on the type of error. For example:
fetch(url)
.then(response=>{
console.log(response.ok);
response.text();
})
.catch(
if (err instanceof TypeError) {
// Handle this normally
} else {
// Execute other logic depending on the type of error you are receiving
}
);
Hope this helps, good luck :)

Access SonarQube API with FetchAPI doesn't return any result

I am trying to access SonarQube API through Fetch but it doesn't seem to be responding with any results. It just resolves with an opaque token.
Let me share what I have done so far:
fetch("http://localhost:9000/api/issues/search?pageSize=500&componentKeys=bactch_analysis_key",{
mode:'no-cors'
}) // Call the fetch function passing the url of the API as a parameter
.then(
res => res.json()
)
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
I am setting the mode as no-cors as it was throwing ACAO errors.
The same URL works perfect when openend from chrome or inspected through Postman.
This is what I get when the promise resolves:
Below is the error that I get from the catch clause:
SyntaxError: Unexpected end of input
at fetch.then.res (index.html:51)

Categories