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