Differences in Javascript with throwing and return error

Junchen Pan
3 min readApr 20, 2020

--

This blog is to differentiate the throwing an error with returning an error. In project, I found different people have different ways of handling errors, but when people work together, this kind of mixture can generate a real error. And I want to take a step back to discuss about the difference, so that people can handle their errors consciously.

First of all, let’s see what happen if we throwing an error

this will cause the thread stop working, we can see the console never gets executed.

Now if we add a try catch, we can see the thread will keeping working and let you handle the error in the catch block.

And even if it is the nested function throwing the error, the catch can handle the error at the outer function level, the thread can still work.

Okay, now let’s see another style of error handling (The Golang way)

So here we handle error by returning it instead of throwing. You can see you have more granularities of error message here, and it is safer, it won’t accidentally stop the whole thread if you forget to try catch, and it is more readable. But we also have a drawback, if we want to add a new error in the very inner function call like inner10(), then we gonna return the error level by level, that’s error-prone and unpleasant to do so.

Better solutions? Yes, we could see that these two type of errors handling are not conflicting each other at all, we can choose to the second style if we want more granularity control of messages and we can choose to the first style if we just want to catch the error inside multiple depth of functions.

This example shows, I really don’t care the error details beyond inner2, if any layer throws, just catch it in the inner1, and in the main(), we can clearly test result.error to see if any error returned.

Overall, the two ways of error handling really provide flexibilities and conveniences on how you want to handling your errors. I am not saying the best way to do error handling, because there is no such case. Find out what works in your case and what kind of error you want to log or recover from.

Welcome any thoughts on this, always appreciate better ideas :)

--

--

Junchen Pan

Keep learning all those great thoughts around the world. Back End Developer, Nodejs, Typescript.