JS Hack🤯: Error handling using both .then and .catch is same !?

In this Blog we will see that is there any difference in doing Error handling(catching error) through .then and .catch.

FACT : The second parameter for .then is for catching the errors 🤯, don't believe me?, see yourself.

 

CODE

const promise1 = new Promise((resolve, reject) => {
    //resolve('Success!');

    oihrg; //this line is intentionally written to produce error.
    //reject('failed!');

});

promise1.then (
    (value) => {
        console.log(value); // expected output: "Success!"
    }
    , // this comma separates both arguments of .then
    (err) => console.log("An error catched inside .then - ",err) //👈this is it !
)
.catch (err => console.log("catched by .catch - ",err));

OUTPUT

"An error catched inside .then - " ReferenceError: oihrg is not defined 

 

NOTE :- Precedence is given to the second second argument of .then over .catch i.e. if a Promise fails then it'll be first catched inside the second argument of .then. So, use the either one only.

CONCLUSION :- Both methods of Error handling are same, so you may use either one, but using .catch makes our code slightly more readable.

Comments

Popular posts from this blog

Mastering Retention - The power of Spaced repetition and Deliberate Practice

Free & Easy Designing tools for a Software Developer

My Advice to my Juniors, My Biggest College mistakes - Raw