Reputation:
I am new to javascript and I need to handle constraint error in sequelize. I searched related to this topic everywhere, but still, I couldn't get a proper workable answer. My attempt it as follows.
app.post('/api/users', (req, res) => {
try {
console.log(req.body);
User.create(req.body)
.then(user=> res.json(user));
} catch (error) {
console.log("Error: "+error);
}});
Here couldn't catch the exception yet. For a valid user input it is able to post the request. So I just need to know a way to handle the exception.
Upvotes: 5
Views: 11833
Reputation: 108
Was looking around for an answer for this, but was not really satisfied with the two given. If you are looking to return a correct response such as a 403 this is the solution I have came up with.
app.post('/api/users', async (req, res) => {
try {
console.log(req.body);
var user = await User.create(req.body)
return res.status(200).json({ status: 'success', result: res.json(user) })
} catch (error) {
if (error.name === 'SequelizeUniqueConstraintError') {
res.status(403)
res.send({ status: 'error', message: "User already exists"});
} else {
res.status(500)
res.send({ status: 'error', message: "Something went wrong"});
}
}
});
Upvotes: 8
Reputation: 2375
Looks like you're mixing two different styles. If you're using then()
, then the try catch block is unnecessary:
app.post('/api/users', (req, res) => {
console.log(req.body)
User.create(req.body)
.then(user => res.json(user))
.catch(error => console.log('Error: ' + error))
})
The other style would be using the async package. With async, your code would look like this:
app.post('/api/users', async (req, res) => {
console.log(req.body)
try {
const user = await User.create(req.body)
res.json(user)
}
catch (error) { console.log('Error: ' + error) }
})
Both methods have their advantages and disadvantages that go beyond this snippet and lot of people use both as appropriate, for example the await
approach works only inside a function declared with async
like in the second example :async (req, res)
. In such cases, using then()
style promise handling is a better approach
Upvotes: 0
Reputation: 1838
You can use Promise
with .then().catch()
, or use async/await
with try/catch
This is Promise
app.post('/api/users', (req, res) => {
console.log(req.body);
User.create(req.body)
.then(user=> res.json(user))
.catch(err => console.log(err))
});
This is async/await
app.post('/api/users', async (req, res) => {
try {
console.log(req.body);
const user = await User.create(req.body);
res.json(user);
} catch (error) {
console.log("Error: "+error);
}
});
Upvotes: 3