When a promise is called in the client side. What is the best way to catch/display error without console.log()? Example as follows
.then(result => {
})
.catch(err => {
console.log(err);
});
Maybe you are looking for:
console.error = () => { throw new Error(FEATURES_ERROR); };
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
Related
exports.postDeleteProduct = (req, res, next) => {
const prodId = req.body.productId;
Product.findById(prodId)
.then((product) => {
return product.destroy();
})
.then((result) => {
res.redirect("/admin/products");
})
.catch((err) => console.log(err));
};
TypeError: Product.findById is not a function
I am getting "TypeError: Product.findById is not a function."
I am using the mysql database and retreiving the data using sequelize. But it is showing error when I gone to alter the values(editing and deliting) in the databse.
I tried findByAll() .But it is giving the 500 status in the network console.
In sequelize ORM findById is not there instead of that u can try below code
exports.postDeleteProduct = (req, res, next) => {
const prodId = req.body.productId;
Product.findByPK(prodId)
.then((product) => {
return product.destroy();
})
.then((result) => {
res.redirect("/admin/products");
})
.catch((err) => console.log(err));
};
Or Else u can use findOne instead of findByPk
Happy Coding :)
I created 3 functions: findOne, create and update. Respectively the methods are GET, POST, PUT.
I changed my API path, it used to be /api/users/:id, now it's /api/users/:sub.
routes.js:
module.exports = app => {
const users = require("../controllers/user.controller.js");
const router = require("express").Router();
// Create a new User
router.post("/", users.create);
// Retrieve a single User with sub
router.get("/:sub", users.findOne);
// Update a User with sub
router.put("/:sub", users.update);
// Delete a User with sub
router.delete("/:sub", users.delete);
app.use('/api/users', router);
};
controller.js:
// Save User in the database
User.create(user)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the Users."
});
});
};
// Find a single User with an id and sub
exports.findOne = (req, res) => {
const sub = req.params.sub;
User.findOne({sub})
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message: "Error retrieving User with id=" +sub
});
});
};
// Update a User by the sub in the request
exports.update = (req, res) => {
const sub = req.params.sub;
User.update(req.body, {
where: { sub }
})
.then(num => {
if (sub) {
res.send({
message: "User was updated successfully."
});
} else {
res.send({
message: `Cannot update User with sub=. Maybe User was not found or req.body is empty!`
});
}
})
.catch(err => {
res.status(500).send({
message: "Error updating User with sub="
});
});
};
What I wanted to do was: check if the user_id provided by the authentication provider was present in my database.
If yes, update user data with that user_id.
If not, create a new user record
This is the front-end part involved:
//INFO SAVE AND UPDATE CONDITION
const userExist = InfoDataService.get(data.sub)
.then((response) => {
console.log('find', response.data);
return true;
});
if ( userExist ) {
InfoDataService.create(data)
.then((response) => {
console.log('create', response.data);
setInfo({
id: response.data.id,
sub: response.data.sub,
email: response.data.email,
firstname: response.data.firstname,
lastname: response.data.lastname,
});
})
} else {
InfoDataService.update(sub, data)
.then((response) => {
console.log(response.data);
})
.catch((e) => {
console.error(e);
});
}
};
I thought userInDatabase could only give true or false, so I used it as an argument in the if statement. It does not work and just updates.
If you need any other information, please ask, I have just started and I hope I have given the necessary info.
EDIT
Through findOne I can find the entire object in my database, but I thought that putting the function as an if condition could give me true if it found the object with its sub; false if he found nothing.
This is not the case, in fact in the code I just updated, although findOne works correctly, it continues to execute always and only create.
router.get("/stocks/symbols", function (req, res, next) {
req.db
.from("stocks")
.select("name","symbol","industry")
.modify(function(queryBuilder) {
if (req.query.param) {
queryBuilder.where('industry',req.query.param);
}
})
.where('timestamp', '=', '2020-03-24T00:00:00Z')
.then((rows) => {
res.json(rows)
})
.catch((err) => {
console.log(err)
res.json({ Error: false, Message: "Error in MySQL query" })
})
})
I'm trying to make such a functionality to use querystring.
At the moment this runs without error but doesn't do anything.
Whether I put ?industry=h or anything after the route, it returns the same data.
There was an example I followed, but for some reason its not working.
What else am i missing?
router.get("/stocks/symbols/:industry", function (req, res, next) {
req.db
.from("stocks")
.select("name","symbol","industry")
.where('timestamp', '=', '2020-03-24T00:00:00Z')
.where("industry", "like", `%${req.params.industry}%`)
.then((rows) => {
res.json({ Error: false, Message: "Success", Cities: rows })
})
.catch((err) => {
console.log(err)
res.json({ Error: true, Message: "Error in MySQL query" })
})
})
This does similar job that i want to do but it doesn't use the querystring.
You need to apply the correct query parameter - in your code you use query.param meaning that your url would need to contain /stocks/symbols?param=tbd
If you're expecting industry as a query-param, you need to change it to:
.modify(function(queryBuilder) {
if (req.query.industry) {
queryBuilder.where('industry',req.query.industry);
}
})
I want to get data from form and based on that, add data to three tables in mySQL, I use Sequelize to do so, However I don't how to do so, my current idea gives error:
Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers
after they are sent to the client
My code is like this:
app.post("/device/add", (req, res) => {
db.Devices.create({
device_id: req.body.device_id,
server: req.body.server,
type: req.body.type
})
.then(result => {
res.json(result);
})
.catch(err => {
throw err;
});
db.Modules.create({
device_id: req.body.device_id,
device_options: req.body.device_options,,
sleep_options: req.body.sleep_options
})
.then(result => {
res.json(result);
})
.catch(err => {
throw err;
});
db.Tests.create({
device_id: req.body.device_id,
gsm_tests: req.body.gsm_tests,
led_tests: req.body.led_tests,
})
.then(result => {
res.json(result);
})
.catch(err => {
throw err;
});
});
can I somehow create it in one response? Or how to make it work
The problem is that you are trying to send again a response after you have sent one.
For more clarification, refer here
You can use Promise.all() to accumulate the results and then send it in one res.json() call.
const createDevice = db.Devices.create({
device_id: req.body.device_id,
server: req.body.server,
type: req.body.type
})
const createModules = db.Modules.create({
device_id: req.body.device_id,
device_options: req.body.device_options,
sleep_options: req.body.sleep_options
})
const createTests = db.Tests.create({
device_id: req.body.device_id,
gsm_tests: req.body.gsm_tests,
led_tests: req.body.led_tests,
})
Promise
.all([createDevice , createModules , createTests ])
.then(result=> {
res.json({
devices: result[0],
modules: result[1],
test : result[2]
});
})
.catch(err => {
throw(err);
});
I have programme in nodejs & mysql like below
db.query()
.then(1)
.then(2)
.then(3)
.catch()
I am checking a value from database in then(1) and trying to return response from there.In then(2) , I am executing another code that uses some data from result of then(1) and so on..
My problem: When returning response from then(1), catch() is calling(because then(2) have error, not getting data from then(1)) . So is there any way I can stop further execution in then(1) so that then(2) and catch() couldn't call ?
db.query('query......', [val1, val2])
.then(rslt => { return res.json({ mssg: "Email already exists!", error: "Email already exists!" }) })
.then(user => { return db.query('INSERT INTO ', value, (err, res, flds) => { err ? reject(err) : resolve(res) }) })
.then(user => { return res.json({ mssg: "Success", success: true}) })
.catch( (err) => { console.log(err) })
You can (and should) use an async function, instead of using the lower-level .then() API of the Promise object:
async function doTheThing() {
try {
const result = await db.query('...');
if (result) { // user exists
return res.json({...}); // this will end the entire function
}
const user = await db.query('...');
return res.json({...}); // success
} catch (err) {
console.log(err); // I don't recommend doing this. try/catch should be for recovery
}
}