G to the SQUARE

Occasionally, I write my opinions on software development.

Handling errors in promises the DRY way

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));

// ...

I recently used this with dynamic imports.

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:


//...

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 />);
// ...

If you have a complex build and you have enabled caching but you still don't see any significant improvements, then the culprit might be that you haven't enabled babel caching:

Read more...

Every software project has a need for periodic refactoring. We need to add more tests (if any), improve readability and decrease tech debt. Otherwise the code base becomes hard to work with and deployments, well... “deployment jenga”:

Read more...