Skip to content

Instantly share code, notes, and snippets.

@ericpkatz
Last active April 3, 2021 15:04
Show Gist options
  • Save ericpkatz/ead6bf849a51c7da3d7b51ca7c6fd365 to your computer and use it in GitHub Desktop.
Save ericpkatz/ead6bf849a51c7da3d7b51ca7c6fd365 to your computer and use it in GitHub Desktop.

Issue - the "swallowing" of errors

  • a swallowed error in a thunk will prevent a component from detecting the error

  • a swallowed error in a Sequelize method will prevent an express route from detecting the error

  • both of these often result in difficult to detect bugs

  • I think this is a valid example with Sequelize. You can imagine the createByName method being called in an express route, but I'm just using it to seed the database.

const Sequelize = require('sequelize');
const { DataTypes: { STRING } } = Sequelize;
const conn = new Sequelize(process.env.DATABASE_URL || 'postgres://localhost/acme_db');

const User = conn.define('user', {
  name: STRING(4)
});

User.createByName = async function(name){
  try {
    return await this.create({ name });
  }
  catch(ex){
    console.log(ex);
  }
};

const syncAndSeed = async()=> {
  await conn.sync({ force: true });
  await User.createByName('moe');
  await User.createByName('larry');//this won't work, max 4 characters
};
  • demonstration of a bug is shown in the code below.
syncAndSeed()
  .then( ()=> {
    console.log('seeded');//BUG this still prints because of swallowed error
  })
  .catch( ex => console.log(ex));//BUG there was an error but we don't catch it
  • note in the createByName method I am swallowing the error. If you see code which catches an error, and does nothing with it, then it is swallowing the error. Usually not a good sign.

  • the solution is to catch the error and throw it or to not catch it at all

User.createByName = async function(name){
  try {
    return await this.create({ name });
  }
  catch(ex){
    console.log(ex);
    throw ex;
  }
};

or even better

User.createByName = function(name){
    return this.create({ name });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment