Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you escape try/catch hell in Javascript?

Ok, I like(d) try/catch with await/async.

But what do I do with this.

I wanted to do this..

let a = await doAbc();
let b = await do123(a);

what it becomes instead is

let a, b;

try {
   a = await doAbc();
} catch(e) {
   a = await doZxc();
}

try { 
   b = await do123(a);
} catch (e) {
   console.log(e);
   return;
}

if (b.data == undefined) {
    return -1;
} else {
    return b;
}

At this point I'm regretting everything.

like image 932
Muhammad Umer Avatar asked Oct 26 '18 02:10

Muhammad Umer


People also ask

Does try catch stop execution JavaScript?

The “try… First, the code in try {...} is executed. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch . If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err) .

Is there a try catch in JavaScript?

JavaScript try and catch The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Can you nest try catch blocks JavaScript?

You can nest one or more try statements. If an inner try statement does not have a catch -block, the enclosing try statement's catch -block is used instead. You can also use the try statement to handle JavaScript exceptions. See the JavaScript Guide for more information on JavaScript exceptions.


1 Answers

Remember that you can await any promise. So you could do:

let a = await doAbc().catch(doZxc); // or .catch(() => doZxc())
let b = await do123(a);

Or even

 let b = await doAbc().catch(doZxc).then(do123);

Together with the rest of your code:

try { 
  let b = await doAbc().catch(doZxc).then(do123);
  return b.data == undefined ? -1 : b;
} catch (e) {
   console.log(e);
   return;
}
like image 68
Felix Kling Avatar answered Sep 20 '22 03:09

Felix Kling