How to catch errors on the frontend from the backend?

  • 0
    The crux 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 you send a request with incorrect fields on the frontend, 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?
    JavaScript Aiden Harding, Nov 22, 2020

  • 3 Answers
  • 0
    The server response needs to be processed. 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 ...
    Lucas Garrison

  • 0
    The error must be in the request body.

    Client error handling depends on how you send requests (fetch, axios, etc.).

    As a rule, the body of the error response can be obtained in the catch of the promise.



    If this is a fetch, then the erroneous response must first be parsed (response.json () or response.text ()). In addition, by default, a fetch does not reject a promise if the response did not come with a status of 200, so this should also be handled.

    if (response.status >= 200 && response.status < 300) {
    return Promise.resolve(response);
    } else {
    return Promise.reject(response.json())
    }
    Anonymous

  • 0

    1. Add field validation to the front. Better not to make mistakes at all.

    2. I do not understand who is determining the error on the back-end. And what a mistake.

    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!