Answer the question
In order to leave comments, you need to log in
How to catch errors on the frontend from the backend?
The essence of the question is this:
there is a list of errors on the backend, for example:
res.status(400).send({ message: 'Incorrectly ID' });
res.status(400).send({ message: 'Incorrectly Email' });
Answer the question
In order to leave comments, you need to log in
We need to process the server response. Check its status or statusCode.
As an example:
fetch('http://localhost:3001/register', {
method: 'post',
body: data
})
.then(response => {
if (!response.ok) {
throw new Error('my api returned an error')
}
return response.json()
})
.then(user => {
console.log(user)
})
The error must be in the body of the request.
Error handling on the client depends on how you send requests (fetch, axios, etc.).
As a rule, the body of an erroneous response can be received in the catch of the promise.
If this is a fetch, then the erroneous response must first be parsed (response.json() or response.text()). Also, by default fetch will not reject a promise unless the response came with a status of 200, so that needs to be handled too.
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response);
} else {
return Promise.reject(response.json())
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question