How can I catch error 401 when making a post using Reactjs Xios on a login screen?

Asked

Viewed 708 times

-2

I’m making a login screen, I have a function that posts an API sending user and password, and gets a token back from being correct (so far so good), or returns error 401, which is shown in the console for me.

I wanted to pick up this error and play on an Alert on the screen when the user or password is wrong.

I tried so:

 try{
              apiPost({
                username:this.state.email,
                password: this.state.password
              }).then((chave) => {
                this.setState({token: chave});
                this.setState({redirect: '/logado'});
              
              });
            
            }catch(erro){
              //console.log(erro);
              alert('Usuario ou senha inválidos!');
            }

But it seems that it does not fall in the catch, because this Alert that I placed is not launched on the screen, maybe because it is right, but returns with code 401?

imagem do console ao errar usuario

My API function is:

export default function apiPost(data){
  
    return(
      axios.post('https://minhaapi/api/login',data)
      .then((response) => {
        console.log('RESPOSTA',response.data);
        if(response.status === "sucess"){
        return response.data.token;
        }
        return response.data.status
      })
    );
}

I tried to use the status, unsuccessfully, when the data is right, it returns the token right, and I redirect, when the error, it shows the message on the console, and only! want to inform a message, where should I do it ? and how ?

  • Could show your api code?

2 answers

1

I’ll post an example code but with the same idea of the code you made:

Consider the function apiPost as the code below:

const requestQueDaraSucesso = () => (
  fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
)

const requestQueDaraErro = () => (
  fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(() => {
      throw new Error('401')
    })
)

Above I am using a fake API just to explain. In the first function we will have a request where the data will be returned, and in the second, an error, like the API returning this - only it would return a 401 in the header and everything.

Now the code that would call its function apiPost:

const funcaoQueFaraRequest = () => {
  requestQueDaraErro()
    .then(resposta => {
      console.log('sucesso - ', resposta)
    })
    .catch(resposta => {
      console.log('erro - ', resposta)
    })
}

As the function requestQueDaraErro is a Promise, I’m doing your treatment using then/catch. Another way to do it would be:

const funcaoQueFaraRequest = async () => {
  try {
    await requestQueDaraErro()
  } catch (resposta) {
    console.log('erro - ', resposta)
  }
}

That way, you make use of the try/catch, but for that you need to use the async/await of Js.

0

It’s not falling in the catch because this function is not returning any errors. The function returns a status if it is different from sucess and this data is not considered error pro tryCatch. Puts tryCatch in Function apiPost. If the call returns an error, it will automatically fall into the catch, then you can treat the error message and display an Alert.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.