DEV Community

Discussion on: Handling Asynchronous Errors Like a Pro

Collapse
 
adderek profile image
Maciej Wakuła • Edited

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

server.listen('/fail', (req, res) =>{
   return new Promise(resolve=>{
       resolve(() =>{
           res.send(()=>{
               return Promise.resolve(() =>
                  process.on('unhandledError', () =>
                     throw new Error(() =>res.set('error', true)
                  )
                  return true
           })
       } ) 
   }) 
}) ;
Enter fullscreen mode Exit fullscreen mode

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.