G to the Square

Handling errors in promises the DRY way

2018-10-28

Here I will show you a subtle abstraction when dealing with errors in promises. The core concept using the Promise.resolve as we do in express middlewares with next().

function renderTemplate () {...}

//...

request({ url })
  .then(res => Promise.resolve(res.data))
  .catch(err => Promise.resolve({err}))
  .then(data => renderTemplate(data));

// ...

The example is kind of dumb implementation, but let say that renderTemplate knows how to handle a error in the request. The above code illustrates how you can handle data in a promise without the need of calling the renderTemplate twice (once in the catch and once in the first then).

Even better, sometimes the error handling is done by some other component, then you could do something like this:

function renderTemplate () {...}

//...

request({ url })
  .then(res => Promise.resolve(res.data))
  .catch(err => {
    // reports the error
    renderError(err); 
    // return empty data object 
    // which component should know how to handle
    return Promise.resolve({})) ;
  }
  .then(data => renderTemplate(data));

// ...

The above pattern worked well because the file that I dynamically imported was data that was optional for a component. So, in this case I just needed to pass the data to the corresponding prop without the need to call rendering of the component in the catch and then. Instead it will look like this:

I recently used this with dynamic imports.


//...

import(/* webpackChunkName: "someConfig" */ 'someConfig')
  .then(({ default: config }) => Promise.resolve(config))
  .catch(err => {
    // reports the error
    print.error(err); 
    // return empty data object 
    // which component should know how to handle
    return Promise.resolve({})) ;
  }
  .then(config => <Component prop=config />);
// ...
Geries Handal Profile picture

Occasionally, I write my opinions on software development. By Geries Handal. Github, Gitlab

Copyright © 2020 Geries Handal