Home > Software design >  Axios error handler message with async/await in the react
Axios error handler message with async/await in the react

Time:05-18

My app requests axios from the react to the nestjs server, and the code is here.

const loginEvent = async (id, password) => {
    try {
      const res = await (await axios.post('users/login', { id, password })).data;
      if (res.success) {
         ...
      } else {
         ...
      }
    } catch (err) {
      console.log('Login Err ', err);
    }
  };

In Postman, I could see properly including messages and success.

{
    "success": false,
    "statusCode": 400,
    "timestamp": "2022-05-17T11:50:16.676Z",
    "path": "/users/login",
    "message": [
        "id should not be empty"
    ],
    "error": "Bad Request"
}

However, only brief error messages are displayed in React.

POST http://localhost:3000/users/login 400 (Bad Request)
Login Err  Error: Request failed with status code 400
    at createError (createError.js:16:1)
    at settle (settle.js:17:1)
    at XMLHttpRequest.onloadend (xhr.js:66:1)

When an error occurs in the request, the server sends a handled messages and success = false, but neither was found in the response of axios using async/wait.

If i don't use async/wait, I can check both at axios.post.then.catch(), but I want to use async/wait to make the code cleaner. What should I do?

CodePudding user response:

If the server send the array message, you should be able to get them in the response object in your error, as below:

async function loginEvent() {
  try {
    const res = await (await axios.post('users/login')).data
    // your code
  } catch (e: any) {
    const statusCode = e.response.status // 400
    const statusText = e.response.statusText // Bad Request
    const message = e.response.data.message[0] // id should not be empty
    console.log(`${statusCode} - ${statusText} - ${message}`)
  }
}

Hope it helps !

  • Related