-
there is something that I've seen in some of our workshops and solutions that I think are a bit problematic, which I wanted to address.
-
basically it's the "swallowing" of errors. I see the issue in Sequelize models and in thunks
-
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
-
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
};
syncAndSeed()
.then( ()=> {
console.log('seeded');//BUG this still prints because of swallowed error
})
.catch( ex => console.log(ex));-
note in the createByName method I am swallowing the error. If you see code which catches an error and doing nothing with it, then it is swallowing the error. Usually not a good sign.
-
the solution is to not catch the error if you are going to swallow it (no catch) or catch it but then throw it
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 });
};