The function createPool takes a callback, that will present an error if something went wrong with the connection. I want to throw an exception in case that happens Connection pool failed with error, but for some reason it keeps being unhandled and the try catch doesn't catch it. What can I change ?
try {
// Create a connection pool which will later be accessed via the
// pool cache as the 'default' pool.
await oracledb.createPool({
user: dbConfig.user,
password: dbConfig.password,
connectString: `${dbConfig.host}:${dbConfig.port}/${dbConfig.serviceId}`
}, (err) => {
if (err) {
throw `Connection pool failed with ${err.message}`;
} else {
console.log('Connection pool started');
}
}
)
} catch (err) {
console.log(err);
// propagate
throw err;
}
The exceptions is thrown inside the callback as expected:
(node:32) UnhandledPromiseRejectionWarning: Connection pool failed with ORA-24415: Missing or null username.
But I can't catch her in my outer try catch
Related
Context
I want to execute a comand line call in the backend of my website. If this comandline call fails, I want to catch the error and throw a new custom Error.
I tried to throw the error as follows:
async function someFunction(): Promise<void> {
...
const result = exec(`some command`);
result.on('error', (error) => {
console.log(error.message);
throw error;
});
}
and
async function someFunction(): Promise<void> {
...
exec(`some command`, (error) => {
if (error) {
throw error;
}
});
}
and catch it like this:
try {
await someFunction();
} catch (e) {
...
throw new Error('Meaningfull error')
}
Problem
But the code never reaches the catch block, as it shuts down the second i reacht the throw error.
Error: Command failed: some Command: Kommando nicht gefunden. //(Command not found)
at ChildProcess.exithandler (node:child_process:398:12)
at ChildProcess.emit (node:events:527:28)
at ChildProcess.emit (node:domain:475:12)
at maybeClose (node:internal/child_process:1092:16)
at Socket.<anonymous> (node:internal/child_process:451:11)
at Socket.emit (node:events:527:28)
at Socket.emit (node:domain:475:12)
at Pipe.<anonymous> (node:net:709:12) {
code: 127,
killed: false,
signal: null,
cmd: 'some Command'
}
Waiting for the debugger to disconnect...
[nodemon] app crashed - waiting for file changes before starting...
I tried removing the error handeling attempt and the app keeps on minding its own business. I don't understand why it keeps crashing when I trie to handle an error...
I am aware, that the command fails, and I don't care. I just want to be able to handle the error.
Edit 1
I also tried a try catch arround the exec call.
try {
exec(`some Command`, (error) => {
if (error) {
throw error;
}
});
} catch (e) {
throw e;
}
But sadly the app crashes right at the throw error line.
Edit 2
I use an restify middleware based error handler
this.restify.on('uncaughtException', function(req, res, route, err) {
res.send(500, err.message);
});
As an example. The Following code is beeing handled as expected:
if (!newUser.course) {
console.log('no course selected');
throw new Error('signal/no-course'); // error is thrown and handled accordingly
}
try {
await someFunction(newUser); // error in someFunction is thrown and crashes the app...
} catch (e) {
console.log(e);
throw new Error('signal/add-user');
}
I also tried adding console.log(error) in every catch. Didn't help.
Hello I think the correct way to approach this would be to wrap it into a Promise since it is an error within a callback, if you actually want to try and catch the error where it happens, it has to be done inside the callback as far as I am aware.
Possible solution:
function someFunction() {
return new Promise((resolve, reject) => {
exec(`some command`, (error) => {
if (error) {
reject(error);
}
resolve("coding is fun 😀");
});
})
}
async function main() {
try {
await someFunction();
} catch (e) {
console.error(e)
throw e;
}
}
I'm using mongoose + express to build a simple MERN app.
I need to create multiple documents and save them, but I need to catch all errors.
I'm using this code and it works, but I'd like to handle all errors at once, not repeat the same code multiple times.
If I use try...catch block and remove the callback error handler, I obtain UnhandledPromiseRejectionWarning.
model.save((err, doc) => {
if (err) return console.error(`ERR ${err.message}`);
});
I've tried this:
export const init = async () => {
try {
const newDoc = new MyModel({ test: 'test'});
const savedDoc = await newDoc.save();
console.log('All done :)');
} catch (err) {
console.log('Error');
res.status(400).send(err);
}
}
But I can't catch the error: in debug mode, the program never enter the catch block and I obtain, in case of error for example:
UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection
Any suggestion?
model.save()
.then(success => {
if(!success) {
// Handle your error
}
// Success
return model2.save();
})
.then(success2 => {
})
// etc..
.catch(err => {
// Handle your error
});
try{
const savedModel = await model.save();
console.log("Model created successfully");
res.status(200).send("Model created successfully");
}catch (err){
console.log(err);
res.status(400).send(err);
}
I am building a simple login/register app. I am testing the login part. Whenever I input a wrong login, however, the backend (written in NodeJS and Express) crashes and stops.
Previously my code threw an error whenever the SQL returned error like so:
con.query("SELECT * FROM table_name WHERE username=" + usernameGiven, function(er, result) {
if (er) throw er;
return result;
}
This worked but had the issue as told above. So I removed the throw er part and replaced it with console.log(er) but still the nodeJS would stop and further login attempt will throw a CORS error.
So how can I stop it from doing and make it just log it and continue to the next request?
Edit:
I tried try and catch as shown below:
try {
con.query(sql_query, function(er, result) {
if (er) {
console.log(er);
}
response.json(result);
})
} catch (er) {
console.log(er);
}
However this still shows an error:
/home/x/CodeOver/LoginForm/api/node_modules/mysql/lib/protocol/Parser.js:437
throw err; // Rethrow non-MySQL errors
^
TypeError: Cannot read property 'password' of undefined
at Query.<anonymous> (/home/x/CodeOver/LoginForm/api/api.js:43:37)
at Query.<anonymous> (/home/x/CodeOver/LoginForm/api/node_modules/mysql/lib/Connection.js:526:10)
I'd suggest a little refactoring to make the code more robust to this type of failure.
The try .. catch blocks won't actually catch query errors in this situation, though I'll leave them there in case of any other error.
We should also use parameters here when querying. SQL Injection attacks are bad news and using parameters will also make the query less likely to result in a syntax error.
I'd also fail early and throw back a 400 error if our usernameGiven is not present.
Here is the updated code, I hope this helps you!
try {
if (!usernameGiven) {
response.status(400).send("Bad Request");
return;
}
let sql_query = "select * from table_name where username = ?";
con.query(sql_query, [usernameGiven], function(er, result) {
if (er) {
console.error("Error occurred:", er);
response.status(500).send("Internal Server Error")
} else {
response.json(result);
}
})
} catch (er) {
console.error("Error occurred:", er);
}
I'm pretty new on NodeJS and I'm still trying to figure out how to handle errors. I read a lot of questions but I don't realize what I'm doing wrong.
Here I have a login function:
export const login = async (req, res) => {
let body = req.body;
try {
const user = await User.findOne({ username: body.username });
if (!user) {
throw new InternalError("Username or password are wrong");
}
if (!bcrypt.compareSync(body.password, user.password)) {
throw new InternalError("Username or password are wrong");
}
let token = jwt.sign({ data: user }, "secret", {
expiresIn: 60 * 60 * 24 * 30
});
return res.json({
user: user,
token: token
});
} catch (error) {
throw new GenericError(error);
}
};
And this is the error I get if, for example, I include a wrong password:
(node:12332) UnhandledPromiseRejectionWarning: GenericError: Username or password are wrong
(node:12332) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by
throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
I know the promises made with Await must have a .then() and .catch() but this is not an error on executing the promise but on validating the password.
What I want is to throw the error and get the response. Right now the request never ends and the previous error is displayed.
Thank you!
PS: InternalError and GenericError are just errors created by me which extends from Error
You receive the warning from node because you are re-throwing a GenericError after catching InternalError. Instead of re-throwing the GenericError, you should return your response or catch your GenericError when calling login.
Here is your code modified for both.
export const login = async (req, res) => {
// We get the body info
let body = req.body;
try {
// We find the user with the username from the body
const user = await User.findOne({ username: body.username });
// Let's assume no user exists, so we throw an InternalError,
// This skips straight to the catch block.
if (!user) {
throw new InternalError("Username or password are wrong");
}
// We never reach these two statements
// because of the error above being thrown.
if (!bcrypt.compareSync(body.password, user.password)) {
throw new InternalError("Username or password are wrong");
}
let token = jwt.sign({ data: user }, "secret", {
expiresIn: 60 * 60 * 24 * 30
});
res.json({
user: user,
token: token
});
} catch (err) {
// We caught our InternalError from not having a user above.
// Now we should return a response that the user is invalid.
// I am just going to return the error that we previously threw.
res.json({
error: err
});
}
};
You can definitely throw the GenericError from your catch block. However, doing that then requires you to catch the GenericError wherever you are calling your login function.
export const login = async (req, res) => {
// We get the body info
let body = req.body;
try {
// We find the user with the username from the body
const user = await User.findOne({ username: body.username });
// Let's assume no user exists, so we throw an InternalError,
// This skips straight to the catch block.
if (!user) {
throw new InternalError("Username or password are wrong");
}
// We never reach these two statements
// because of the error above being thrown.
if (!bcrypt.compareSync(body.password, user.password)) {
throw new InternalError("Username or password are wrong");
}
let token = jwt.sign({ data: user }, "secret", {
expiresIn: 60 * 60 * 24 * 30
});
res.json({
user: user,
token: token
});
} catch (err) {
// Throw the generic error
throw GenericError(err);
}
};
try {
// We call the login function that is defined above.
// It is going to throw a GenericError, so we have to
// catch it.
await login(req, res);
} catch (err) {
// Now we need to catch the generic error
res.json({
error: err
});
}
I am connecting Oracle database using express.js.
oracledb.getConnection(config, function (err, connection) {
if (err) console.log(err);
connection.execute("SELECT * FROM database", function (error, results, fields) {
if (error) {
console.log(error);
res.json({
status: false,
message: "there are some error with query"
})
} else {
if(results !="" && results!= null && results!= undefined){
res.json({
data: results,
status: true,
message: "Data get from db"
})
}
}
})
})
The problem is that when I am running API I got the following error in cmd:
TypeError: Cannot read property 'execute' of undefined'
So after getting this error, I have searched and I got a solution. Then I change my code in the following way:
(async function () {
try {
connection = await oracledb.getConnection({
user: 'xyz',
password: 'xyz',
connectString: 'xyz'
});
result = await connection.execute("SELECT * FROM database");
res.json({
data: result,
status: true,
message: "Data get from db",
length: results.length
})
} catch (err) {
console.error(err.message);
} finally {
if (connection) {
try {
await connection.close(); // Always close connections
} catch (err) {
console.error(err.message);
}
}
}
})();
But after implementing this asynchronous way, I got another errro:
can not locate oracle 64bit client library: "some path.../oci.dll is not the correct architecture"...
UnhandledPromisePejectionWarning: connection is not defined....
UnhandledPromisePejectionWarning: this error is originated either by throwing inside of an async function without a catch, block or by rejecting a promise which was not handled with .catch()
What am I doing wrong?