Clash Royale CLAN TAG#URR8PPP
How can I catch rejected Promises?
My code is as follows:
errorTest().then((result) => {
try {
console.log(result);
}
catch (err) {
console.error("Error detected 1");
console.error(err);
}
}).catch((err) => {
console.error("Error detected 2");
console.error(err);
});
async function errorTest() {
return new Promise((resolve, reject) => {
reject("my error");
})
}
Currently, it prints "Error detected 2".
I would like to catch my error using try / catch such that the code prints "Error detected 1".
How do I modify my code to do this?
then
3 Answers
3
first when you declare async function that means you declare a function that returns a Promise. so you don't need to warp it with new Promise
async
you can just do
async function errorTest() {
throw new Error("my error")
}
then you can catch it with try catch like this
(async () =>{
try{
await errorTest()
}
catch(err){
console.log(err)
}
})()
then the full code will look like this
async function errorTest() {
throw new Error("my error")
}
(async () =>{
try{
await errorTest()
}
catch(err){
console.log(err)
}
})()
The problem is that an error is being thrown in the errorTest function, which happens first, that means that the .catch function is called instead of .then.
errorTest
.catch
.then
async function errorTest() {
return new Promise((resolve, reject) => {
reject("my error");
})
}
try {
var result = await errorTest()
try {
console.log(result);
} catch (err) {
console.error("Error detected 2");
console.error(err);
}
} catch (err) {
console.error("Error detected 1");
console.error(err);
}
you can do something like this
//no need to make it async
function errorTest() {
return new Promise((resolve, reject) => {
reject("my error");
})
}
async function test(){
try{
await errorTest();
try{
console.log(result);
//try some syncronous task.
}
catch(e){
console.error("Error detected 1");
console.error(err);
}
}
catch(err){
//if promise returned by errorTest() is rejected; rejected value: err
console.error("Error detected 2");
console.error(err);
}
}
test(); //this also returns a promise though.
Hope, this helps.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You're trying to catch error in success handler, see
then's syntax– barbsan
yesterday