Asynchronous operations, such as fetching data from external APIs or handling user interactions, introduce complexities that demand error handling ...
For further actions, you may consider blocking this person and/or reporting abuse
Interesting post. Personally, I prefer the try catch approach. I try to avoid the
promise.thensyntax since it can be hard to understand the execution flow.I prefer a mix of both await and .then/.catch, since try-catch is usually outside of the promise chain, so you cannot pinpoint where the error happened unless you wrap every single promise in a try-catch-block, which breaks the reading flow:
Good point! Never thought about it.
You have a good point. Actually, depending on the context, each approach may offer distinct advantages.
I love this. Though would add a bit. You should handle process.on and things like sigterm. You should use a context of the call. Async local storage is your friend. Either promise or async (async is a promise under the hood) and don't mix with callbacks. Callback that returning rejected promise throwing an error is a nightmare. Don't catch any error and make sure that error leads to action. Often I prefer server to crash because this enforces user/operator to solve the issue while handled messages are often neglected (if it works then errors are ignored even if "payment failed" but you were able to pick item from the shop).
Now imagine the ugly code
I am not sure if the above works - just wanted to show how a nightmare can look like.
Oh... And it should fail in the delayed error handling failing to send headers that were already sent.
Thank you for introducing me to the
unhandledRejectionevent.Glad to help!
Nice post thank you 👏
In browsers or JS runtimes that implement the Web API one could use
addEventListener("unhandledrejection", eventHandler).Also I often need to implement retry strategies for my async functions (in case of network error or else). I came up with a tiny utility called Tentative that simplifies the process: github.com/sim-la/tentative, but I'll be curious to hear what others use for handling retries in async functions.