JavaScript try/catch block - javascript

export const getData = async (locationId) => {
try {
return await axios.get(`/api/data/?lotion=${locationId}`);
} catch (error) {
console.log('ERROR', error);
}
};
So I have function getData where I added try/catch block.That function is called in another component in componentDidMount() and its all working if endpoint is correct but if I try to make error its not running my catch block. I mistyped my endpoint the correct one is /api/data/?location=${locationId} I have done that to get error and I get error 400 Bad Request. So the problem is that my code never run my catch block and it doesn't console.log Error.
I found similar problem on internet and they said that async/await must be added I also added that but still not working...
Any ideas?

Related

What is the best practice in this situation Async Await with try/catch or Promise.then().catch()?

I try to create a function that returns values ​​from the server, if one of the values ​​returns with an error then everything that comes back to me from the function falls and I get NULL,
If I use try / catch the problem is solved.
What is the best solution in terms of performance and something that can work in the result I want
public async getUserById(id: number): Promise<dto> {
const arr = [];
const user = await this.userService.getUserById(id);
try {
const company = await this.companyService.getCompanyIdToken(
user.company_id
);
UsersProvider.setUserCompany(user, company);
for (const space of user.spaces) {
try {
const Response = await this.companyService.getSpaceById(space);
arr.push(Response);
} catch (error) {
console.log(error) **// Here I expect you not to throw an error**
}
}
} catch (error) {
console.log(error) **// Here I expect you not to throw an error**
}
return user;
}
As others have explained, in terms of performance, there isn't really a difference between try/catch and catch.
However, in my experience, try/catch statement are much clearer for peer reviews and maintenance (for error message management), but that is just a personal preference.
Moreover, if getSpaceById() can throw synchronously, then you do have to catch that synchronous exception with try/catch if you ever wish to use the .then() statement (you will get an error if you only use.catch() instead of try/catch). You might as well use the try/catch now before getting an error.

Node.js catch statement return does not stop executing

I'm trying to create a discord bot with the help of node.js
In which I need to call a function that may return discord API errors I handle them like this
interaction.user.send("Hi")
.catch(() => {return interaction.reply("...");
console.log("shouldnt run if an error accured")
However whenever that API error accurse the return statement unlike normally does not stop the code execution.
How do I stop the console.log statement in this code from executing when the exception accurse ?
the js is asynchronous so it puts the request of API in execution queue(not wait for response from api) and continue its execution that's why your console statement is running even if the error occurs.
interaction.user.send("Hi")
.then(() => {
// do whatever you want when it succeed
})
.catch((error) => {
// handle error
});
you can also checkout async await for the same.
As #ParthPatel indicates, interation.user.send() is returning a Promise which may not be rejected immediately upon error. Statements such as your console.log() will run before an error has a chance to occur and be caught.
However, these days there is the async await syntax you can use, which may help you simplify your code a bit depending on what you're trying to do.
try {
await interaction.user.send("Hi");
console.log('Shouldn\'t run if error occurred.');
} catch(e) {
interaction.reply('...');
}
Note that you can only use await inside of an async function, declared like this:
async function doSomething() {
// Do something here...
}
You can find more information here: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

Discord.js use try catch statement to handle api error

Hello I am currently attempting to catch a discord api error with the try catch statement
However for some reason this does not work and my app still stops executing and gives me the following message
There was an uncaught error DiscordAPIError: Cannot send messages to this user // Example
How do I catch api errors with a try and catch block and I cannot use a .catch expression after calling the function
Here is my code
try {
interaction.user.send("Remember")
}
catch(DiscordAPIError) {
console.log("Oh no")
}
If you want to use a synchronous try/catch block, you need to put it in an async function and await the promise from interaction.user.send:
await interaction.user.send("Remember")

Unable to print error message from function call

I am not a JavaScript guy (can only write simple JS function), I am trying to debug a code with the JS where my backed system is passing the correct values but I am getting an error while processing the code on the UI. Here is the JS code
this.session.onvalidatemerchant = function (event) {
this.performAuthorizeMerchantRequest(event.validationURL)
.then(function (merchantSession) {
this.session.completeMerchantValidation(merchantSession);
alert("jdshhdjhjdhh");
}.bind(this))
.catch(this.showPaymentError.bind(this));
}.bind(this);
Here is the error handling function
showPaymentError: function () {
//showing a message on the UI
}
I have already verified the data being passed from my backed service is correct, I don't see the following alter alert("jdshhdjhjdhh");. There seems to be issue with the completeMerchantValidation method but I am not sure what is the root cause for failure.I tried to change my error message with something like this
showPaymentError: function (e) {
console.log("*****111"+e)
}
but getitng the following output in the console *****111TypeError: Type error. Is there a way I can print the error from the completeMerchantValidation. Even tried to add try and catch around that method call but getting js compilation error
Try this. the try catch will handle the potential error which come from performAuthorizeMerchantRequest or completeMerchantValidation.
this.session.onvalidatemerchant = async ({ validationURL }) => {
try {
const merchantSession = await this.performAuthorizeMerchantRequest(validationURL)
this.session.completeMerchantValidation(merchantSession)
alert('jdshhdjhjdhh')
} catch (error) {
console.error('Oh oh, an error happened', error)
this.showPaymentError(error);
}
}
The root cause is a TypeError that is being thrown at some point in the Promise's lifecycle.
Given that console.log("*****111"+e) prints *****111TypeError: Type error, we are dealing with a TypeError.
Unfortunately "Type error" isn't the most useful debugging data :(
Maybe try printing the stacktrace?
https://developer.mozilla.org/en-US/docs/Web/API/Console/trace

Error catched by then instead of catch of Promise - React Native

I am having a problem when calling two async functions in React Native.
Here is code (I just changed the names):
getItems()
.then((response) => {
setItems(response.data);
})
.catch((err) => console.log('getItems', err));
getOtherItems()
.then((response) => {
console.log('response.data', response.data);
setOtherItems(response.data);
})
.catch((err) => console.log('getOtherItems', err));
When the first function throws an error, the error is correctly catched by the catch. But, when the second functions breaks, the error passes through then instead of catch.
The logs are like this:
getItems <Error>
response.data <Error>
Any idea why this is happening?
EDIT:
getItems and getOtherItems make an HTTP call using axios to an external service that returns an array of items.
EDIT 2:
Code for getItems and getOtherItems:
getItems() {
return axios.get('an URL');
}
getOtherItems() {
return axios.get('another URL');
}
EDIT 3:
I realized the first function throws a 500 error while the second logs a 404. So, the problem may be with how the services return the error.
EDIT 4:
It seems the problem is an error in the service. I'll let you know once it's confirmed. Thanks!

Categories