Home > Net >  How do I render API error responses in reactJS axios nodeJS?
How do I render API error responses in reactJS axios nodeJS?

Time:09-17

i need to render the errors that my API gives me, like res.status(422).json({ error: error.message }), and the message it brings me is password validation. I tried using some axios tools but nothing works, like .catch. Can you help me?

React:

function Register() {
  const [email, setEmail] = useState(``);
  const [name, setName] = useState(``);
  const [password, setPassword] = useState(``);

  async function onSubmit(event) {
    event.preventDefault();

    async function handleSubmit() {
      const response = await axios.post("http://localhost:3001/usuario/register",{
          email,
          name,
          password,
        },{
          headers: { "Content-Type": "application/json" },
        }
        
      );
      console.log(response.data);
      const { data } = response;
      return data
    }
    await handleSubmit();
  }

  return (
    <div>
       ...
    </div>
  )
}

NodeJS:

async adicionaRegistro(infosReg, res) {
    
    const dataCriacao = moment().format("YYYY-MM-DD h:mm:ss");
    const status = 1;
    
    const name = infosReg.name;
    const email = infosReg.email;
    const password = infosReg.password;

    try {
      const usuario = new Usuario({
        name,
        email,
        dataCriacao,
        status
      });

      res.status(201).json();
    } catch (erro) {
      if (erro instanceof InvalidArgumentError) {
        console.log(erro)
        res.status(422).json({ erro: erro.message });
      } else if (erro instanceof InternalServerError) {
        res.status(500).json({ erro: erro.message });
      } else {
        res.status(500).json({ erro: erro.message });
      }
    }
  }

CodePudding user response:

What about try...catch to catch the error? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

function Register() {
  const [email, setEmail] = useState(``);
  const [name, setName] = useState(``);
  const [password, setPassword] = useState(``);

  async function onSubmit(event) {
    event.preventDefault();

    async function handleSubmit() {
      let response;
      try {
        response = await axios.post(
          "http://localhost:3001/usuario/register",
          {
            email,
            name,
            password,
          },
          {
            headers: { "Content-Type": "application/json" },
          }
        );
      } catch (e) {
        console.log(e);
        // here you will see the result if your backend is throwing an error
      }
      if (response) {
        console.log(response.data);
        const { data } = response;
        return data;
      }
    }
    await handleSubmit();
  }

  return <div>...</div>;
}
  • Related