In this short article, we are going to see how we can handle error in JavaScript in Golang style.
I am assuming, you have some experience with JavaScript and you are aware of the issues with error handling like throwing an exception to the parent method from try-catch block or chaining multiple then-blocks and implementing logic inside it. These things can easily mess up with the code making it difficult to read.
Golang avoids these type of problems by handling errors/exceptions atomically.
Error handling in Golang
result, err := methodCall()
if err != nil {
// handle error
}
// do something with the result
We can use a similar pattern in JavaScript with the help of a try-catch
block like this.
const getData = async () => {
try {
const result = await methodCall();
return [result, null];
} catch(error) {
return [null, error];
}
}
If any error occurs, we are returning the error
in the second position of the array and the result
as null in the first position.
If there is no error, we are returning the result
in the first position and error
as null in the second position.
Now we can call the getData
method then handle the result
and error
like this.
const [result, error] = await getData();
if (error !== null) {
// handle the error
}
// do something with the result
This pattern of error handling makes it very easy to read and understand the code.
Let me know what do you think about this pattern.
Originally published on blog.bibekkakati.me
Thank you for reading 🙏
If you enjoyed this article or found it helpful, give it a thumbs-up 👍
Feel free to connect 👋
Twitter | Instagram | LinkedIn
If you like my work and want to support it, you can do it here. I will really appreciate it.
Top comments (31)
You can actually turn this into a utility function, like so:
You could also use an object like Brendan said.
I would wrap it in a higher order function though, something that takes an async function and returns a new async function with the added catch logic
Something like this, I guess:
Yeah. That can be way of implementing it.
Yeah. Utility function can be very helpful.
I added a callback
onLoading
so I can do somenthing while function is running.const { data, error } = await promiseHandler(callbackFn, { onLoading: value => console.log('is loading?', value) })
👨🏼💻
Better yet, just use GoLang.
Good idea. 😉
Of course it is! Everyone knows Go is the best language objectively.I've reconsidered. . .
Thinking back, I spoke very unwise words.
It should be "Better yet, just use Rust." — Rust's error handling is exceptional. :þ
Nice, but I would personally use an object instead of the array as a return type
I prefer array because if we use object, destructuring will be an issue if there is more than one block in same level. Also we need to be aware of the property name.
Property name can be set by convention across your whole project. Let's say
{ error, result }
which is to me most verbose and would not lead to accidental access compared to array indicesYeah, that is right. But in case of multiple blocks in the same scope it can create issue, as you will not be able de-structure it like this
But in case of array, you can use other variable name in the second method call.
Feel free to correct me, if I am missing something.
a few ways you could avoid this:
Im not saying the array descructuring is worse, its just a prefference
You can rename the variable when destructuring an object.
@jsnanigans Yeah, It's just a preference.
@erikhofer I am aware of that.
I'm not a huge fan of this pattern.
The idea of explicitly returning errors rather than throwing unchecked errors is great, but the proposed implementation is flawed - we need to always check the elements of the tuple before using the value to see if there is an error which will become error-prone rather quickly.
Fortunately, this is an already solved problem, known in other langues as
Either
orResult
type, in which all of theseifs
are abstracted away in form ofmap
andflatMap
/chain
operations.Potential implementation: gigobyte.github.io/purify/adts/Eit...
Got your point. After all it's all about own preference.
I saw this in a Fireship video, ditto 👀
Is it? Need to check it.
I saw this in a 3 years old article.
in typescript
Can just do
if (error)
though.Yeah, we can do that. Sometimes I just like to check explicitly.
Nice idea. Thanks for sharing :)
I'm glad that you liked it. 😊
Got it. Thank you for sharing that.