I'm using Express to build a REST API with Objection.js ORM. One of my controller's method has a chain of Promises:
register(req, res) {
// ...
indicative.validateAll(req.body.data, rules)
.then(
() => {
const data = {
...req.body.data,
password: bcrypt.hashSync(req.body.data.password, bcrypt.genSaltSync()),
password_confirmation: undefined,
customer: {}
};
return models.User.query()
.insertGraph(data);
}
)
.catch( // catch block 1
(error) => {
console.log(error);
return response.error(res, 422, 'Dados de cadastro inválidos.');
}
)
.then(
(user) => {
return response.success(res, 'Usuário cadastrado com sucesso.', {
user: user
});
}
)
.catch( // catch block 2
(error) => {
console.log(error);
return response.error(res, 500, 'Erro interno, tente novamente.');
}
);
}
When an exception is caught on the first .catch()
block, it returns the response with an error, but the chain keeps executing, and even if I don't return anything in the 1st catch block, the chain continues to the next .then()
.
Is this the expected behavior? If so, how can I "break the chain" or something like that.