This code works fine to upload image to cloudinary.
Let's say the image is uploaded but then there is a mongodb error.
Then I want to delete the image that is already at cloudinary but how can i get the value of "cloudinary_id" in my catch block?
createGalery: async (req, res) => {
try {
const result = await cloudinary.uploader.upload(req.file.path, {
folder: 'Test'
});
let image = result.secure_url;
let cloudinary_id = result.public_id;
const newGalery = new Galery({
image,
cloudinary_id,
});
await newGalery.save();
res.json({ msg: 'successful' });
} catch (err) {
try {
console.log(cloudinary_id);
// How to delete when mongodb save fails?
//await cloudinary.uploader.destroy(result.public_id);
} catch {
return res.status(500).json({ msg: err.message });
}
return res.status(500).json({ msg: err.message });
}
}
Nest your try blocks:
createGalery: async (req, res) => {
try {
const result = await cloudinary.uploader.upload(req.file.path, {
folder: 'Test'
});
const cloudinary_id = result.public_id;
try {
const newGalery = new Galery({
image: result.secure_url,
cloudinary_id,
});
await newGalery.save();
} catch (mongoErr) {
console.log(`Removing ${cloudinary_id} due to failed save`);
await cloudinary.uploader.destroy(cloudinary_id);
throw mongoErr;
}
res.json({ msg: 'successful' });
} catch (err) {
return res.status(500).json({ msg: err.message });
}
}
Move the declaration of your cloudinary_id variable outside of the try/catch block:
let cloudinary_id;
try {
// ...
cloudinary_id = result.public_id; // without the "let" keyword in front of it
// ...
} catch (err) {
console.log(cloudinary_id);
if (cloudinary_id) {
await deleteFromCloudinary(cloudinary_id);
// if cloudinary_id is not set, the error was thrown
// before setting it (i.e. while uploading to cloudinary)
}
}
This code was built to allow us to save errors to our database.
const logErrors = function (data) {
try {
let error = { date: new Date(), ...data };
databaseConnections[dbMappings['BACKEND_ERROR_DB_MAPPING']['default']].collection('BackendLogs').insert(error);
} catch (error) {
const slackLog = new Log();
slackLog.error(error.toString());
}
};
export default logErrors;
The code works OK and saves errors to our database, but it occasionally throws the error "0, logger 1.default) is not a function."
What could be the problem?
Example scenario
catch (error) {
// error.stack = error.stack + " " + JSON.stringify(this.data);
if (error) {
logErrors({ message: error }); <<<<<
}
}
I am trying to throw an error to the calling function and the error is not getting captured. The exception is not propagating to the calling function.
'use strict';
const { Pool } = require('pg');
const pool = new Pool();
var result;
exports.handler = async (event) => {
var payload = event;
try{
result = await insertOrder(payload, 'test');
}
catch (err) {
console.error("Error from main: " + err);
throw err ;
}
return result;
};
async function insertOrder(payload, name)
{
const client = await pool.connect();
try{
const queryString = {
text: "INSERT INTO public.orders(payload, shop_name)" +
"VALUES ($1, $2) RETURNING id",
values: [payload, name],
};
const result = await client.query(queryString);
var orderId = result.rows[0].id;
}
catch (err) {
await client.query('ROLLBACK');
console.log("Error from child: " + err);
throw err;
}
finally {
client.release();
return orderId;
}
}
Here is what is written to the log:
INFO Error from child: error: INSERT has more target columns than expressions
The console.error in the calling function is not written to the log. What am I am missing? TIA!
Moving return orderId; to try block solved my issue
My question is similar to this.
However, mine runs in Node.js and it seems like a bit more complicated.
The server side wasn't built by me, but someone else that I can't contact. And he wrote code very differently.
And I have db.js and it looks like this:
And routes/email.js it uses db.js like this:
And when I click a button. I get this error:
db.emailRequest is not a function
in db.js, at the end of the file. It originally had this:
module.exports = new dbHelper;
And my style to use db.js in routers.
db.get().query(sql, input, function(err,res){
//TODO:
});
But it didn't work. So, I changed the end of db.js like this:
exports.get = function(){
console.log("exports.get");
return pool;
}
And also added some code in app.js like this:
db.connect(function(err){
if(err){
console.log('Unable to connect to MariaDB');
process.exit(1);
}
});
What should I do?
The full code of db.js is here:
const mariadb = require('mariadb');
var pool;
exports.connect = function(done){
console.log("Trying to connect DB...");
pool = mariadb.createPool({
host: 'localhost',
user: 'root',
password: 'xxxxxxx',
database:"XXXXX",
connectionLimit: 5 // Why 5 ???
});
pool.getConnection()
.then(conn => {
console.log("DB connected. id: " + conn.threadId);
conn.end(); //release to pool
}).catch(err => {
console.log("DB failed connection: " + err);
});
}
function makeToken(){
console.log("makeToken()");
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for(var i=0;i<32;i++){
text+=possible.charAt(Math.floor(Math.random()*possible.length));
}
return text;
}
function dbHelper() {
console.log("dbHelper()");
this.emailRequest = function(email,num){
console.log("emailRequest");
pool.getConnection().then(conn => {
conn.query("INSERT INTO email_verification(email, code) VALUES(?,?)",[email,num]);
conn.end(); //release to pool
})
.catch(err => {
console.log("not connected due to error: " + err);
});
}
// wait and process until getting return value because rv is needed.
this.verify = async function(email,num){
console.log("verify");
let conn;
var result = false;
try {
conn = await pool.getConnection();
// within 3minutes
const rows = await conn.query("SELECT count(*) FROM email_verificaiton WHERE email=? AND code=? AND req_time >= NOW() - INTERVAL 3 MINUTE",[email,num]);
if(rows[0]["count(*)"]>0){
result = true;
}
} catch (err) {
throw err;
} finally {
if (conn) conn.end();
}
return result;
}
this.verifyUpdate = function(email,num){
console.log("verifyUpdate");
pool.getConnection()
.then(conn => {
conn.query("UPDATE email_verification SET status = 1 WHERE email=? AND code=?",[email,num]);
conn.end(); //release to pool
})
.catch(err => {
console.log("not connected due to error: " + err);
});
}
// wait and process until getting return value because rv is needed.
this.emailRegister = async function(email,pass,nick,devid){
console.log("emailRegister");
let conn;
var result;
try {
conn = await pool.getConnection();
var rows = await conn.query("SELECT count(*) FROM email_verification WHERE email=? AND status = 1",[email]);
if(rows[0]["count(*)"]>0){
rows = await conn.query("SELECT count(*) FROM member WHERE email=?",[email]);
if(rows[0]["count(*)"]==0){
var token = makeToken();
rows = await conn.query("INSERT INTO member (email,password,username,device_id,login_method,token) VALUES(?,?,?,?,0,?)",[email,pass,nick,devid,token]);
if(rows["affectedRows"]>0){
result = {result:true, code:200, message: "success",data:[{email:email,token:token}]};
} else{
result = {result:false,code:401, message:"db error"};
}
}else {
result = {result:false,code:402, message:"already registered id"};
}
} else {
result = {result:false,code:403, meesage:"email not verified"};
}
} catch (err) {
throw err;
} finally {
if (conn) conn.end();
}
return result;
}
// wait and process until getting return value because rv is needed.
this.emailLogin = async function(email,pass,devid){
console.log("emailLogin");
let conn;
var result;
try {
conn = await pool.getConnection();
rows = await conn.query("SELECT * FROM member WHERE email=?",[email]);
if(rows.length==1){
if(rows[0]["password"]==pass){
var token = makeToken();
rows = await conn.query("UPDATE member SET device_id = ?, token = ? WHERE email=?",[devid,token,email]);
console.log(rows)
if(rows["affectedRows"]>0){
result = {result:true,message:"Sign up Success.", code:200, data:[{email:email,token:token}]};
} else{
result = {result:false,message:"db error",code:401};
}
} else {
result = {result:false,message:"wrong password",code:402};
}
}else {
result = {result:false,message:"not registered id",code:403};
}
} catch (err) {
throw err;
} finally {
if (conn) conn.end();
}
return result;
}
}
//module.exports = new dbHelper;
exports.get = function(){
console.log("exports.get");
return pool;
}
I'm creating a childprocess when an express api is called after saving some info in mongodb. This is the api part
router.get("/create", function(req, res) {
let Schema = new New({
Id: crypto.randomBytes(16).toString("hex"),
Status: "Online"
});
Schema.save(function(err) {
if (err) {
console.log(err);
} else {
let child = exec(`node ${modulepath}`, (error, stdout) => {
if (error) {
throw error;
}
console.log(child.stdout);
});
New.update({
"botId": Schema.Id
}, {
"ProcessId": child.pid
}).then((err) => {
if (err) {
console.log(err);
} else {
console.log("pid updated");
}
});
Id = Schema.Id;
module.exports = {
Id
};
}
});
});
What i'm trying to do here is, at the bottom i'm exporting an id which ideally should be exported to the childprocess instance but that is not happening. In the childprocess, if i import the id by const Id = require("./routes").Id; and try to access some info through it by
await New.findOne({
"Id": Id
}, function(err, b) {
if (err) {
throw err;
} else {
//some task
}
});
I'm not able to access the info as mongodb cant get the id. I know i'm going wrong in passing the value to the childprocess part but what is the solution?