so I have a normal thing you would do to find if a file exists and proceed accordingly:
let response = await fetch(url);
if (response.ok) {
//it exists
} else {
//it doesn't
}
Problem is, of course, if it fails it gives me a TypeError: Failed to fetch and my function stops.
Is there a way I can suppress the error?
I cannot change from a fetch function, i've tried everything else and fetch is the best option in my context.
Thanks in advance.
You will need to implement try and catch and it is quite easy to implement it. You can have a look at Try and Catch Documentation
Have a look at the sample code below
try {
let response = await fetch(url);
}
catch(err) {
alert("Error Message : " + err.message);
}
Is there a way I can suppress the error?
You should wrap your function that may cause the error in try...catch.
const fetch = (isFine) => new Promise(resolve => {
if(isFine)
resolve("Normal data");
else
throw new Error("Error msg...!");
});
const myFunction = async (isFine) => {
try {
const response = await fetch(isFine);
console.log(response);
}
catch(err) {
console.log("Oops..." + err.message);
}
}
myFunction(true);
myFunction(false);
Related
In JavaScript Try catch block how to retry the same . am facing once scenario any one ca give the best approach to handle this ?
for Example :
const getMyDetails = async()=>{
try{
await getName();
}catch(err){
//But Above FAIL due to some issue
// so I want to try the same again "getName" here until the success - 'not single time'
}
// Second Method for get data
const getName = async()=>{
try{
here am calling API or any kind of subscription But here its failing so am throwing error
}catch(err){
throw new Error(err);
}
getMyDetails()
Note: may be the fail reason like Databse events or some other subscriptions etc..
instead of calling the method name in catch .. what will be the best approach for retry
Thanks in advance
Just Calling Itself If It Fails Will Do The Job
const getMyDetails = async()=>{
try{
await getName();
}catch(err){
getMyDetails()
}
// Second Method for get data
const getName = async()=>{
try{
// Method
}catch(err){
throw new Error(err);
}
getMyDetails()
Here you can see an example behavior and the implementation logic of calling an async function N number of times, only until no errors are thrown.
// We must be inside of an async function to be able to call await
(async function() {
// Example async function which returns the value only if no errors are thrown,
// otherwise calls itself to retry the async call
async function getMyDetails() {
try {
return await getName();
} catch (error) {
return getMyDetails();
}
}
// Example async function which returns value only if the random number is even,
// otherwise throws an Error (simulating an API error response)
async function getName() {
return new Promise((resolve, reject) => {
let randomNumber = Math.floor(Math.random());
if (randomNumber % 2 === 0) {
resolve("Random Name");
}
reject("Example API Error has occured.")
});
}
let myDetails = await getMyDetails();
console.log(myDetails);
})();
So I am confused about industry-standard implementation. I feel this is a hacky way the way I am doing it right now
I want to display an error message whenever there is an actual error and display a failure message whenever the server return a nonsuccess status
The problem here is when there is an actual error on assignUser() it returns the error and this does not trigger the catch of the first function, so it is handled by the else statement instead and shows a failure message while it is an actual error.
I tried to use throw new Error("error) in the catch of assignUser() but the same issue.
The second concern I have is regarding (200 >= status <300) is there a simpler way to check a successful operation other than checking the status which can be 200, 204 ...?
try {
let status = assignUser(user);
if (status >= 200 && status < 300) {
notify.show("message success");
} else {
notify.show("message failure");
}
} catch (e) {
notify.show("message error");
}
export async function assignUser(user) {
try {......
return resp.status;
} catch (e) {
return e;
}
}
I assume assignUser function is making an api call using fetch. So if you are not using the then catch method to resolve the promise, then the assignUser function has to be an async function.
async function assignUser(user) {
try {
const jsonRes = await fetch(url);
if(!jsonRes.ok) {
notify.show("message failure");
} else {
notify.show("message success");
const result = await jsonRes.json();
return result;
}
} catch (e) {
notify.show("message error");
}
}
Here you don't need another function to check the status and all
and instead of checking with the status code you can use the response.ok property.
Hope this helps
Thanks
So I was playing with Redux-Saga when came to a error handling stuff.
The problem is that the function generator has try catch block and it calls getAllUserColivings function. This function catches the error Request failed with status code 404. I did that on purpose (messed up url). However, the generator does not catched any errors and done success function which is not great.
Here is the generator code (yes, I know that JWT token should not be in localStorage, but it is for now)
try {
const jwtToken = yield localStorage.getItem("jwt");
const colivings = yield getAllUserColivings(jwtToken);
yield console.log(colivings, "coliving");
yield put(updateColivingsSuccess(colivings));
} catch (error) {
yield put(updateColivingsFailure(error));
}
}
Here is the getAllUserColivings function code:
try {
const validation = await getUserIDByJWT(jwt);
let formData = new FormData();
formData.append("strapi_id", validation);
const response = await axios.post(
"http://localhost:8000/includes/settings/colivins.php",
formData,
headers
);
return response.data;
} catch (error) {
return console.log(error.message);
}
};```
You should be returning the whole error, not console.log function.
I'm trying to embed multiple videos to a web page using Vimeo's oEmbed. The idea is to simply enter the url in the CMS which will generate a div for each item containing the code below.
This javascript is doing what I want but only works with the first item. When I check the console there's only one response which contains the JSON metadata for the first item/video.
Probably this is not the best method but is getting the job done, all I need is to make it work for multiple items. Any ideas how can I do that?
Thank you
<div class="vimeo-video" id="[[+ID]]-video"></div>
<div class="vimeo-info" id="[[+ID]]-info"></div>
<script>
const getJSON = async url => {
try {
const response = await fetch(url);
if (!response.ok) // check if response worked (no 404 errors etc...)
throw new Error(response.statusText);
const data = await response.json(); // get JSON from the response
return data; // returns a promise, which resolves to this data value
} catch (error) {
return error;
}
}
console.log("Fetching data...");
getJSON("https://vimeo.com/api/oembed.json?url=[[+myVideoURL]]").then(data => {
document.getElementById("[[+ID]]-video").innerHTML = data.html;
document.getElementById("[[+ID]]-info").innerHTML = '<h2>' + data.title + '</h2>' + data.description;
console.log(data);
}).catch(error => {
console.error(error);
});
</script>
In case somebody with basic javascript skills like me goes through something similar. The problem was a rookie's mistake, I had to use var instead of const.
The reason is because var variables can be updated and re-declared but const variables can neither be updated nor re-declared. So here's the working code:
var getJSON = async (url) => {
try {
var response = await fetch(url);
if (!response.ok)
// check if response worked (no 404 errors etc...)
throw new Error(response.statusText);
var data = await response.json(); // get JSON from the response
return data; // returns a promise, which resolves to this data value
} catch (error) {
return error;
}
};
Searched on many places and also went through many tutorials to deeply understand the async/awiat behavior of the javascript. Here is my code:
var bookAppointment = async (data) => {
return User.findOne({_id: data.user_id})
.then((userfound) =>{
//manipulate user's data and find if in array the specific object exist
var found = await userfound.dataArray.find( function(element){
return element.data == data.user_data
});
//here I want to wait until above result comes to evaulate below condition
if(found)
{
return "Sorry! data does not exist";
}
else
{
return userfound;
}
})
.catch(err => {
return err
});
}
What I want to achieve is to make my if else condition to wait above find function on array of javascript. Here is the error I'm facing:
SyntaxError: await is only valid in async function
I'm unable to understand where I'm wrong! Even my function has keyword async with its definition. Anyone around for a quick help?
At (userfound) =>{...} you're scoping another function.
For await to work, you need it to be something like async (userfound) => {...}
Catch and Then keyword are not used is async/await functions.
var bookAppointment = async (data) => {
var found = await User.findOne({_id: data.user_id});
try {
//do here like in then
} catch (e) {
//error handling
}
}