Search code examples
javascriptaxios

How do I get error from server when I make a request?


I am making a request to the server and if I get an error, I want to console.log it but returns a javascript error instead.

I found this solution online where in my interception I can return the error appropriately but seem not to work.

   Axios.interceptors.response.use(
    response => {
        return response;
    },
    function(error) {
        // Do something with response error
        if (error.response.status === 401) {
            console.log("unauthorized, logging out ...");
            store.commit("logout");
            router.push({ path: "/login" });
        }
        return Promise.reject(error.response);
    }
  );

This is my request:

  Axios.put("/api/auth/request/phone/verify", {
    phone: this.registeredPhone,
    code: this.stashedCode()
  })
    .then(response => {
      console.log(response);
      if (response.data.status == 200 && response.data.success) {
        swal("Success", response.data.data.message, "success");
      }
    })
    .catch(error => {
      // console.log(error);
      console.log(error.response);
    });

Am expecting something like:

{
 "status": 422,
 "success": false,
 "data": {
 "erro": "validation.phone_field_required."
}

but I end up getting: PUT http://localhost:3000/api/auth/request/phone/verify 422 (Unprocessable Entity)


Solution

  • as mentioned in Axios Documents. you should pass valid status code as option to axios. if you dont do that the status code 4XX is an error so it handle by catch block.

    axios.get('/user/12345', {
      validateStatus: function (status) {
        return status < 500; // Reject only if the status code is greater than or equal to 500
      }
    })
    

    so your request wil be change like this:

    axios({
          method: 'put',
          url: '/api/auth/request/phone/verify',
          data: {
            phone: this.registeredPhone,
            code: this.stashedCode()
          },
          validateStatus: (status) => {
            return status < 500;
          },
        }).catch(error => {
    
        }).then(response => {
            console.log(response);
            if (response.data.status == 200 && response.data.success) {
              swal("Success", response.data.data.message, "success");
             }
        })
    

    feel free to ask more question in comments