I want to handle the error when the user intentionally entered the wrong objectId, but when I compressed the error in a function check objectID, I got this error: UnhandledPromiseRejectionWarning: Error: INVALID_ID
function check obejctID :
function checkObjectId(...ids) {
ids.forEach(id => {
const objectId = mongoose.Types.ObjectId.isValid(id);
if (!objectId) throw new MyError('INVALID_ID',404);
});
}
service :
static async updateAuthor(_id, content) {
checkObjectId(_id);
const author = await Author.findByIdAndUpdate(_id, content, { new: true });
if (!author) throw new MyError('CAN_NOT_FIND_AUTHOR', 404);
return author;
}
router :
routerAuthor.put('/:_id',async (req, res) => {
AuthorService.updateAuthor(req.params._id,req.body)
.then(author => res.send({success : true, author}))
.catch(res.onError);
});
app.use((req, res, next) => {
res.onError = function(error) {
const body = { success: false, message: error.message };
if (!error.statusCode) console.log(error);
res.status(error.statusCode || 500).send(body);
};
next();
});
Try to use try catch:
static async updateAuthor(_id, content) {
try {
checkObjectId(_id);
const author = await Author.findByIdAndUpdate(_id, content, { new: true });
if (!author) throw new MyError('CAN_NOT_FIND_AUTHOR', 404);
return author;
} catch (e) {
throw new Error(e);
}
}
Related
Custom error handler:
export const errorHandler: ErrorRequestHandler = (err, _, res) => {
if (err instanceof HttpError) {
res.status(err.statusCode).json({
message: err.message
});
return;
}
res.status(500).json({
message: err.message,
});
};
Handler where I throw the error:
export const registerHandler: Handler = async (req, res) => {
const { username, password } = req.body as {
username: string | undefined;
password: string | undefined;
};
if (!username || !password) {
throw new UnprocessableEntity();
}
try {
const user = await User.register(username, password);
req.logIn(user, (err) => {
console.log(err);
});
res.json({
user,
});
} catch (error) {
throw new BadRequest(error.message);
}
};
The error handler middleware works as expected when everywhere except when it is thrown in catch block of the registerHandler. It's driving me crazy. Can somebody explain why this is so?
middlewares are pipes, in other words functions that runs after another function, so if you want to run an error handler you need to pass the next function to run
export const registerHandler: Handler = async (req, res, next) => {
const { username, password } = req.body as {
username: string | undefined;
password: string | undefined;
};
if (!username || !password) {
// to let express know that the next function to run is an errorhandler you need to pass a parameter to the function next
return next(new UnprocessableEntity());
}
try {
const user = await User.register(username, password);
req.logIn(user, (err) => {
console.log(err);
});
res.json({
user,
});
} catch (error) {
throw new BadRequest(error.message);
}
};
to create error handlers you need to create a function with 4 parameter
error: the error
req: request
res: response
next: next handler
function errorHandler (error, req, res, next) {
if (err instanceof HttpError) {
return res.status(err.statusCode).json({
message: err.message
});
}
return next(error);
}
for this to work you need to specify your error handlers after all your routes
const app = express()
app.use("/api", apiRoutes());
app.use("/more-routes", moreRoutes());
app.use(errorHandler);
app.use(anotherErrorHandler);
This might not be the exact solution you may be looking for, but it might help.
The express js documentation
says:-
Starting with Express 5, route handlers and middleware that return a Promise will call next(value) automatically when they reject or throw an error.
So you don't need try and catch at all.
The above code can be written as:-
export const registerHandler: Handler = async (req, res) => {
const { username, password } = req.body as {
username: string | undefined;
password: string | undefined;
};
if (!username || !password) {
throw new UnprocessableEntity();
}
const user = await User.register(username, password);
req.logIn(user, (err) => {
console.log(err);
});
res.json({
user,
});
};
If any error occurs in await line, the errorHandler will automatically be called, and you don't have to explicitly throw an error.
I am finding it hard to convert this user controllers code to async await. Can someone please help and guide me how can i do it too. So that i can also change any callbacks into async await.
Also if someone can provide a good source so that i can read about async await and how to apply them properly.
const User = require("../models/user")
exports.getUserById = (req, res, next, id) => {
User.findById(id).exec((error, user) => {
if (error || !user) {
return res.status(400).json({
error: "No user was found in DB"
})
}
req.profile = user
next()
})
}
exports.getUser = (req, res) => {
req.profile.salt = undefined;
req.profile.encrypted_password = undefined;
return res.json(req.profile)
}
exports.getAllUsers = (req, res) => {
User.find().exec((error, users) => {
if (error || !users) {
return res.status(400).json({
error: "No users was found in DB"
})
}
return res.json(users)
})
}
exports.updateUser = (req, res) => {
User.findByIdAndUpdate(
{ _id: req.profile._id },
{ $set: req.body },
{ new: true, useFindAndModify: false },
(error, user) => {
if (error) {
return res.status(400).json({
error: "You are not authorized to update this info"
})
}
user.salt = undefined;
user.encrypted_password = undefined;
res.json(user)
}
)
}
It should look something like this:
const User = require("../models/user");
exports.getUserById = async (req, res, next, id) => {
let user = await User.findById(id);
try {
if (!user) {
return res.status(404).json({
error: "No user was found in DB"
});
}
req.profile = user;
next();
} catch (err) {
return res.status(500).json({
error: "Something went wrong"
});
}
};
exports.getUser = (req, res) => {
req.profile.salt = undefined;
req.profile.encrypted_password = undefined;
return res.json(req.profile);
};
exports.getAllUsers = async (req, res) => {
let users = await User.find();
try {
if (users.length < 1) {
return res.status(404).json({
error: "No users was found in DB"
});
}
return res.json(users);
} catch (err) {
return res.status(500).json({
error: "Something went wrong"
});
}
};
exports.updateUser = async (req, res) => {
try {
let user = await User.findByIdAndUpdate(
{ _id: req.profile._id },
{ $set: req.body },
{ new: true, useFindAndModify: false }
);
user.salt = undefined;
user.encrypted_password = undefined;
return res.json(user);
} catch (err) {
return res.status(400).json({
error: "You are not authorized to update this info"
});
}
};
You should send back 404 errors if you cant find any user in the database. 400 means bad request.
You can achieve what you are asking by wrapping the function with Promise. In your example, you should use the solution given by Ifaruki, because mongoose already supports promises.
function waitSeconds(seconds) {
return new Promise(res => {
setTimeout(() => {
res();
}, seconds * 1000)
})
}
async function foo() {
console.log("Hello");
await waitSeconds(5);
console.log("World");
}
Here you can learn more about async in javascript
As i said in the title i am using a npm package called "next-connect" to structure my api. Every api route that i created suffered from this error. This is the error :
Unhandled rejection: TypeError: Cannot read property 'end' of undefined
at next (/var/task/node_modules/next-connect/lib/index.js:43:54)
at next (/var/task/node_modules/next-connect/lib/index.js:49:9)
at next (/var/task/node_modules/next-connect/lib/index.js:58:16)
at next (/var/task/node_modules/next-connect/lib/index.js:49:9)
at next (/var/task/node_modules/next-connect/lib/index.js:58:16)
at next (/var/task/node_modules/next-connect/lib/index.js:58:16)
at next (/var/task/node_modules/next-connect/lib/index.js:60:9)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
After a few minutes of trying i get to solve it in dev. Most of this due to messing with the .env file.
Here the code from my API Route :
import nextConnect from "next-connect";
import bcrypt from "bcryptjs";
import middleware from "../../middlewares/middleware";
const handler = nextConnect();
handler.use(middleware);
handler.get((req, res) => {
if (req.user) {
const { name, email, bio, profilePicture, emailVerified } = req.user;
return res.status(200).send({
status: "ok",
data: {
isLoggedIn: true,
user: {
name,
email,
bio,
profilePicture,
emailVerified
}
}
});
}
return res.status(200).send({
status: "ok",
data: {
isLoggedIn: false,
user: {}
}
});
});
handler.post((req, res) => {
const { email, password } = req.body;
return req.db
.collection("users")
.findOne({ email })
.then(user => {
if (user) {
return bcrypt.compare(password, user.password).then(result => {
if (result) return Promise.resolve(user);
return Promise.reject(Error("The password you entered is incorrect"));
});
}
return Promise.reject(Error("The email does not exist"));
})
.then(user => {
req.session.userId = user._id;
return res.send({
status: "ok",
message: `Welcome back, ${user.name}!`
});
})
.catch(error =>
res.send({
status: "error",
message: error.toString()
})
);
});
handler.delete((req, res) => {
delete req.session.userId;
return res.status(200).send({
status: "ok",
message: "You have been logged out."
});
});
export default handler;
And here code from the next-connect package (the one mentioned in the error report) :
module.exports = () => {
function connect(req, res) {
connect.handle(req, res);
}
connect.stack = [];
function add(method, ...handle) {
for (let i = 0; i < handle.length; i += 1) {
if (handle[i].stack) Object.assign(this.stack, handle[i].stack);
else this.stack.push({ handle: handle[i], method });
}
}
// method routing
connect.get = add.bind(connect, 'GET');
connect.head = add.bind(connect, 'HEAD');
connect.post = add.bind(connect, 'POST');
connect.put = add.bind(connect, 'PUT');
connect.delete = add.bind(connect, 'DELETE');
connect.options = add.bind(connect, 'OPTIONS');
connect.trace = add.bind(connect, 'TRACE');
connect.patch = add.bind(connect, 'PATCH');
// middleware
connect.use = add.bind(connect, '');
connect.error = add.bind(connect, 'ERR');
connect.apply = function apply(req, res) {
return new Promise((resolve) => this.handle(req, res, resolve));
};
connect.handle = function handle(req, res, done) {
let idx = 0;
const { stack } = this;
async function next(err) {
const layer = stack[idx];
idx += 1;
// all done
if (!layer) {
if (done) done();
else if (!res.headersSent) res.writeHead(404).end();
return;
}
// check if is correct method or middleware
if (layer.method !== '' && layer.method !== 'ERR' && layer.method !== req.method) {
next(err);
return;
}
try {
if (!err) { await layer.handle(req, res, next); return; }
// there is an error
if (layer.method === 'ERR' || layer.handle.length === 4) {
await layer.handle(err, req, res, next);
} else next(err);
} catch (error) {
next(error);
}
}
// Init stack chain
next();
};
return connect;
};
I am building a login/Register portion of my app. Right now I'm using express-validator to check if an email exists in my collection.
This is my route:
var router = require('express').Router()
var UserModel = require('../models/UserModel')
var { body } = require('express-validator');
router
.route('/registration')
.get(function(req, res) {
console.log(0)
UserModel.find({}, (err, users) => {
console.log(1);
if (err) return res.status(500).send(err)
console.log(2);
return res.json(users);
})
})
.post(body('username_email').custom(value => {
console.log("value ", value);
console.log(3)
UserModel.findOne({ 'username_email': value }, (err) => {
console.log(4);
if (err) return res.status(409).send(err);
})
}), async(req, res, next) => {
console.log(5)
try {
let newUser = new UserModel(req.body);
let savedUser = await newUser.save();
console.log(6);
if (savedUser) return res.redirect('/users/registration?success=true');
return next(new Error('Failed to save user for unknown reasons'))
} catch (err) {
return next(err)
}
})
module.exports = router
In my component on the front end I have a function in my fetch which will catch the error if there is one.
handleErrors(response) {
if (!response.ok) {
console.log('This email exists!')
throw Error(response.statusText);
}
return response;
}
handleSubmit(event) {
event.preventDefault()
var { username, password } = this.state
var mailFormat = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
var error = false
if (!username.match(mailFormat)) {
this.setState({ usernameError: true })
error = true
} else {
this.setState({ usernameError: false })
}
if (password.length <= 8) {
this.setState({ passwordError: true })
error = true
} else {
this.setState({ passwordError: false })
}
console.log(`error ${error}`)
if (error == false) {
this.setState({ formError: false, formSuccess: true })
}
window.fetch('http://localhost:8016/users/registration', {
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({ username_email: username, password: password })
})
.then(this.handleErrors)
.then(function (response) {
console.log(`response ${response}`)
return response.json()
}).then(function (data) {
console.log('User created:', data)
}).catch(function (error) {
console.log(error);
});
}
The console.log in the fetch, handleErrors is being registered in the console, but why isn't the error status a 409 like I indicated.
Closer excerpt of post route!
.post(body('username_email').custom(value => {
console.log("value ", value);
console.log(3)
Is this the problem? Node style should have a error and callback?
UserModel.findOne({ 'username_email': value }, (err) => {
console.log(4);
if (err) return res.status(409).send(err);
})
}), async(req, res, next) => {
console.log(5)
try {
let newUser = new UserModel(req.body);
let savedUser = await newUser.save();
console.log(6);
if (savedUser) return res.redirect('/users/registration?success=true');
return next(new Error('Failed to save user for unknown reasons'))
} catch (err) {
return next(err)
}
})
UPDATE
I tried Nick's solution but I get this:
MongoError: E11000 duplicate key error collection: development.users index: email_1 dup key: { : null }
at Function.create (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongodb-core/lib/error.js:43:12)
at toError (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongodb/lib/utils.js:149:22)
at coll.s.topology.insert (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongodb/lib/operations/collection_ops.js:859:39)
at handler (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongodb-core/lib/topologies/replset.js:1155:22)
at /Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongodb-core/lib/connection/pool.js:397:18
at process._tickCallback (internal/process/next_tick.js:61:11)
POST /users/registration 500 312.485 ms - 51
^C
Two things I am noticing:
I get back MongoError: E11000 duplicate key error collection: development.users index: email_1 dup key: { : null }
which is the error from having a duplicate email, but number one where is E-mail already in use message in the console from the promise? And two how can I pass the error status "res.status(409).send(err);" from the promise?
The issue was that during your validation, you weren't returning the promise since the mongoose call is async. The rest the code ran before your validator was finished. I commented where you were missing the return.
router.route('/registration')
.get(function(req, res) {
UserModel.find({}, (err, users) => {
if (err) res.status(500).send(err)
res.json(users)
})
})
.post(body('username').custom(value => {
return UserModel.findOne({ 'email': value }).then(user => { // Return Promise
if (user) {
return Promise.reject('E-mail already in use');
}
});
}), async(req, res, next) => {
try {
let newUser = new UserModel(req.body)
let savedUser = await newUser.save(err => {
if (err) return res.json({ success: false, error: err })
return res.json({ success: true })
})
if (savedUser) return res.redirect('/users/registration?success=true');
return next(new Error('Failed to save user for unknown reasons'))
} catch (err) {
return next(err)
}
})
module.exports = router
UPDATE
Just read through express-validator docs. I think you would need to validate the errors during the request process
var router = require('express').Router()
var UserModel = require('../models/UserModel')
var { body, validationResult } = require('express-validator');
router.route('/registration')
.get(function(req, res) {
UserModel.find({}, (err, users) => {
if (err) res.status(500).send(err)
res.json(users)
})
})
.post(body('username').custom(value => {
return UserModel.findOne({ 'email': value }).then(user => { // Return Promise
if (user) {
return Promise.reject('E-mail already in use');
}
});
}), async(req, res, next) => {
// Checks for errors in validation
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
try {
let newUser = new UserModel(req.body)
let savedUser = await newUser.save(err => {
if (err) return res.json({ success: false, error: err })
return res.json({ success: true })
})
if (savedUser) return res.redirect('/users/registration?success=true');
return next(new Error('Failed to save user for unknown reasons'))
} catch (err) {
return next(err)
}
})
module.exports = router
I have a following Post route
router.post("/message", async (req, res) => {
const newMessage = new Message({
From: req.body.sendersPhoneNumber,
To: 9188123560,
OTP: req.body.randomNumber,
Message: req.body.TextToSend
})
newMessage.save().then((response) => {
const from = "NEXMO"
const to = response.To
const text = response.Message
nexmo.message.sendSms(from, to, text, {type: 'unicode'}, (error, responseData) => {
if (error) {
console.log(error)
throw new Error (error)
} else {
console.dir(responseData)
res.send(responseData)
}
})
})
})
In this, I want to throw an error If there is an error for which i did something like this
if (error) {
console.log(error)
throw new Error (error)
}
But that doesn't seem to be working, can some help me by sharing, how can we throw an error in nodeJs
This is my request from frontend
axios.post(test_url_base + "/contact/message", this.state).then(response => {
Solution 01:
Line 1: Need a third parameter, next to pass the error to the next handler.
Line 16: pass the error to the next error handler, return next(error);
NB: In your root file like index.js or server.js or whatever you are using, You need an error handler, like,
app.use((err, req, res, next) => {
console.log('Found a error');
});
Your final code will be,
router.post("/message", async (req, res, next) => {
const newMessage = new Message({
From: req.body.sendersPhoneNumber,
To: 9188123560,
OTP: req.body.randomNumber,
Message: req.body.TextToSend
})
newMessage.save().then((response) => {
const from = "NEXMO"
const to = response.To
const text = response.Message
nexmo.message.sendSms(from, to, text, {type: 'unicode'}, (error, responseData) => {
if (error) {
console.log(error)
return next(error);
} else {
console.dir(responseData)
res.send(responseData)
}
})
})
})
Solution 2:
If you encounter an error, pass the error to the client side,
Use res.status(400).send(error);
In this case, your code should be,
router.post("/message", async (req, res, next) => {
const newMessage = new Message({
From: req.body.sendersPhoneNumber,
To: 9188123560,
OTP: req.body.randomNumber,
Message: req.body.TextToSend
})
newMessage.save().then((response) => {
const from = "NEXMO"
const to = response.To
const text = response.Message
nexmo.message.sendSms(from, to, text, {type: 'unicode'}, (error, responseData) => {
if (error) {
console.log(error)
return res.send(error);
} else {
console.dir(responseData)
res.send(responseData)
}
})
})
})
as you have done that is also correct way but i don't get why it is not working.
you can also try this one
if (error) {
return next(error)
}
or you can also do this
res.render('error', { error: err })
Put try catch block , so that any error thrown from try block gets caught in catch block.
router.post("/message", async (req, res) => {
try {
const newMessage = new Message({
From: req.body.sendersPhoneNumber,
To: 9188123560,
OTP: req.body.randomNumber,
Message: req.body.TextToSend
})
newMessage.save().then((response) => {
const from = "NEXMO"
const to = response.To
const text = response.Message
nexmo.message.sendSms(from, to, text, { type: 'unicode' }, (error, responseData) => {
if (error) {
console.log(error)
throw new Error(error)
} else {
console.dir(responseData)
res.send(responseData)
}
})
});
}
catch (e) {
res.send({ status: 400, error: e });
}
})