Answer the question
In order to leave comments, you need to log in
Why doesn't promise.catch() catch the error?
Code without error (works fine):
let userInsert = new Promise((resolve, reject) => {
db.query('INSERT INTO users (email, password) VALUES (?, ?)', [user.email, user.password])
});
userInsert
.catch(function (err) {
console.log('error');
});
let userInsert = new Promise((resolve, reject) => {
db.query('INSERT INTO users (email, passwordError) VALUES (?, ?)', [user.email, user.password])
});
userInsert
.catch(function (err) {
console.log('error');
});
let p = new Promise((resolve, reject) => {
// то же что reject(new Error("o_O"))
throw new Error("o_O");
})
p.catch(alert('error'));
Error: ER_BAD_FIELD_ERROR: Unknown column 'passwordError' in 'field list'
Answer the question
In order to leave comments, you need to log in
You don't resolve or reject anything, so this promise will never go further down the chain.
It is obvious that db.query is asynchronous, but since it did not receive a callback, it throws its exception into the general thread, by this moment the promise handler function has already been successfully completed, naturally it does not catch an error.
Much of course depends on the database driver, but I suspect that you need to do this:
let userInsert = new Promise((resolve, reject) => {
db.query('INSERT INTO users (email, password) VALUES (?, ?)', [user.email, user.password], err => {
if(err) {
reject(err);
return;
}
resolve();
});
});
Well, maybe he catches an error inside himself and displays it in the console. and the promise rejects, for example
Promise.catch is not part of the try/catch statement. promise.catch is just a shortcut for everything that comes promise.then(null, function() {})
with it.
It is advisable to specify which driver for which database you are using. It is strange for me to see a blocking database request in the node.js code when non-blocking calls with callbacks are used for almost any i / o operations. It is possible that you need to manually throw an exception in the callback/reject the promise if err is present, in the callback call after the request
It can only catch synchronous exceptions.
Simple example:
let p = new Promise((resolve, reject) => {
setTimeout(() => {
throw 'WTF';
}, 0);
});
p.catch( console.log );
let userInsert = new Promise((resolve, reject) => {
db.query(
'INSERT INTO users (email, password) VALUES (?, ?)',
[user.email, user.password],
(err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
)
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question