1

I'm developing an application with Next.Js with a separate back end, I'm having a problem handling the error returned by my API in Next when I try to make the authentication. I'm using Axios to make requests.

When I send an incorrect credential (username or password) my API sends a response like this

res.status(400).json({error: "Username or password is invalid!"})

But when I get the error response in the frontend ( Next.Js ) and try to display this message returned in a sweetalert2 alert or in console.log(), only the error code appears, I can't catch this message from error returned

Below is the error message I catch:

Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

And here the code of the function where I make the request and handle it:

 async function signIn({ user, pass }: ILoginRequest) {

    try {
      const result = await api.post('/login', { user, password: pass });

      setUser({
        email: result.data.user_info.email,
        ra: result.data.user_info.ra,
        name_user: result.data.user_info.name_user,
      })

      setCookie(undefined, 'app-token', result.data.token, {
        expires: new Date(result.data.expiresIn)
      })

      Router.push('./home');
    } catch (err) {
      console.log(err)
      Swal.fire({
        title: 'Error!',
        text: err,
        icon: 'error',
        confirmButtonText: 'Aceitar'
      })
    }
  }
Karyl Chesman
  • 23
  • 1
  • 3
  • Does this answer your question: [Axios. How to get error response even when api return 404 error, in try catch finally](https://stackoverflow.com/questions/48298890/axios-how-to-get-error-response-even-when-api-return-404-error-in-try-catch-fi)? You should be able to access the 400 response body through `err.data`. – juliomalves Aug 11 '21 at 20:23
  • @juliomalves perfect, this answer suits me a problem solver. – Karyl Chesman Aug 11 '21 at 20:56

0 Answers0