E
E
Elena2020-11-10 18:15:11
JavaScript
Elena, 2020-11-10 18:15:11

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' });

If the frontend sends a request with invalid fields, then a 400 (Bad Request) response is received, and not with errors from the backend. How to take errors from the backend and if they cannot be taken from there, then why do we write them there at all?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey P, 2020-11-10
@Elena0394

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)
  })

https://developer.mozilla.org/en-US/docs/Web/API/R...

T
twolegs, 2020-11-10
@twolegs

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())
  }

K
Karpion, 2020-11-10
@Karpion

  1. Put on the front check the correctness of the fields. It's better not to make mistakes at all.
  2. I did not understand who on the back determines the error. And what a mistake.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question