1
Good evening guys, I’m beginner with Javascript, and I’m developing the functionality of a CRUD, I want to use the correct HTTP verbs for each function (Obs: I know that using the HTTP verbs is only convention) anyway, my application for testing has the following environment:
- Javascript Vanilla
- Nodejs
- Express
- Mongodb
The Backend part is done, and it’s working normally, I’ll take a route to illustrate:
router.post('/add', async (req, res) => {
if (await User.findOne({ email: req.body.email }))
return res.status(400).send('Error user already exists.');
await User.create(req.body, (err, user) => {
if (err)
return res.status(400).send({ error: 'Failed to insert documents.' });
return res.json(user);
});
});
As the code above informs, is a route to add the user, first check if the user exists in the database, as parameter use the field email because in my Model it is a single item, if it exists it will return an error if not, it will add the user.
As already informed, I tried in several ways to get the following error message:
fetch('/test/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json; charset=utf-8' },
body: JSON.stringify({
name: 'test',
age: '20',
email: '[email protected]',
gender: 'male',
developer: 'yes',
}),
})
.then(res => {
if (res.ok) {
return res.json();
} else {
return Promise.reject({ status: res.status, statusText: res.statusText });
}
})
.then(res => console.log(res))
.catch(err => console.log('Error, with message:', err.statusText));
I forced an error by adding the same data that has already been entered and as already said the field email is unique, so internally Mongodb would blow an error, I treat him in Backend, but in Frontend I have no control.
I’d really like to use Async/Await and be able to control error messages, and also wanted the answer in which my Backend returns to be seen on Frontend too, someone could help me?
It’s hard to predict any mistakes. It is worth remembering that in the creation of a user can be predicted if the user already exists and send this error message, but there are errors that it is good to be dealt with in the Front-end, eliminate all errors do not think valid and also that the excess of errors is also not good need a compromise
– novic
Http verbs denote a pattern and should be followed, I don’t think it’s just convention
– novic
@Virgilio Novic, yes I want to treat the errors in Frontend the last code does it but, but it’s simply as if the handling of the errors simply did not exist, are ignored, bursts X error for me, i wanted to show a more user friendly message but am not getting, you know some way for me to get around this?
– Magno