Axios получить код ошибки

This may seem stupid, but I’m trying to get the error data when a request fails in Axios.

axios
  .get('foo.example')
  .then((response) => {})
  .catch((error) => {
    console.log(error); //Logs a string: Error: Request failed with status code 404
  });

Instead of the string, is it possible to get an object with perhaps the status code and content? For example:

Object = {status: 404, reason: 'Not found', body: '404 Not found'}

Stephen Ostermiller on Strike's user avatar

asked Aug 25, 2016 at 19:13

Sebastian Olsen's user avatar

Sebastian OlsenSebastian Olsen

10.3k9 gold badges45 silver badges91 bronze badges

What you see is the string returned by the toString method of the error object. (error is not a string.)

If a response has been received from the server, the error object will contain the response property:

axios.get('/foo')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    }
  });

answered Aug 25, 2016 at 19:34

Nick Uraltsev's user avatar

Nick UraltsevNick Uraltsev

24.3k4 gold badges25 silver badges14 bronze badges

17

With TypeScript, it is easy to find what you want with the right type.

This makes everything easier because you can get all the properties of the type with autocomplete, so you can know the proper structure of your response and error.

import { AxiosResponse, AxiosError } from 'axios'

axios.get('foo.example')
  .then((response: AxiosResponse) => {
    // Handle response
  })
  .catch((reason: AxiosError) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

Also, you can pass a parameter to both types to tell what are you expecting inside response.data like so:

import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.example')
  .then((response: AxiosResponse<{user:{name:string}}>) => {
    // Handle response
  })
  .catch((reason: AxiosError<{additionalInfo:string}>) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

Stephen Ostermiller on Strike's user avatar

answered Sep 17, 2019 at 3:03

Yan QiDong's user avatar

3

As @Nick said, the results you see when you console.log a JavaScript Error object depend on the exact implementation of console.log, which varies and (imo) makes checking errors incredibly annoying.

If you’d like to see the full Error object and all the information it carries bypassing the toString() method, you could just use JSON.stringify:

axios.get('/foo')
  .catch(function (error) {
    console.log(JSON.stringify(error))
  });

answered Feb 14, 2017 at 9:17

danii's user avatar

daniidanii

5,5432 gold badges21 silver badges23 bronze badges

2

There is a new option called validateStatus in request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:

const {status} = axios.get('foo.example', {validateStatus: () => true})

Stephen Ostermiller on Strike's user avatar

answered Mar 31, 2020 at 12:44

Dmytro Naumenko's user avatar

You can use the spread operator (...) to force it into a new object like this:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({...error})
})

Be aware: this will not be an instance of Error.

Stephen Ostermiller on Strike's user avatar

answered Jan 22, 2020 at 20:31

Moses Schwartz's user avatar

Moses SchwartzMoses Schwartz

2,8071 gold badge19 silver badges31 bronze badges

0

I am using this interceptors to get the error response.

const HttpClient = axios.create({
  baseURL: env.baseUrl,
});

HttpClient.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.resolve({ error });
});

answered Dec 5, 2016 at 16:41

Tan's user avatar

TanTan

3323 silver badges11 bronze badges

2

In order to get the http status code returned from the server, you can add validateStatus: status => true to axios options:

axios({
    method: 'POST',
    url: 'http://localhost:3001/users/login',
    data: { username, password },
    validateStatus: () => true
}).then(res => {
    console.log(res.status);
});

This way, every http response resolves the promise returned from axios.

https://github.com/axios/axios#handling-errors

answered May 7, 2020 at 11:48

Emre Tapcı's user avatar

Emre TapcıEmre Tapcı

1,72315 silver badges16 bronze badges

Whole error can only be shown using error.response like that :

axios.get('url').catch((error) => {
      if (error.response) {
        console.log(error.response);
      }
    });

answered Jul 1, 2021 at 10:07

Manik Verma's user avatar

const handleSubmit = (e) => {
e.preventDefault();
// console.log(name);
setLoading(true);
createCategory({ name }, user.token)
  .then((res) => {
   // console.log("res",res);
    setLoading(false);
    setName("");
    toast.success(`"${res.data.name}" is created`);
    loadCategories();
  })
  .catch((err) => {
    console.log(err);
    setLoading(false);
    if (err.response.status === 400) toast.error(err.response.data);//explained in GD
  });

};

See the console log then you will understand clearly

enter image description here

answered Oct 7, 2022 at 4:08

Shakil- The Coding monster's user avatar

With Axios

    post('/stores', body).then((res) => {

        notifyInfo("Store Created Successfully")
        GetStore()
    }).catch(function (error) {

        if (error.status === 409) {
            notifyError("Duplicate Location ID, Please Add another one")
        } else {
            notifyError(error.data.detail)
        }

    })

answered Sep 3, 2021 at 5:43

Rumesh Madushanka's user avatar

It’s indeed pretty weird that fetching only error does not return an object. While returning error.response gives you access to most feedback stuff you need.

I ended up using this:

axios.get(...).catch( error => { return Promise.reject(error.response.data.error); });

Which gives strictly the stuff I need: status code (404) and the text-message of the error.

answered Apr 27, 2021 at 12:14

Bogdan Antone's user avatar

Axios. get('foo.example')
.then((response) => {})
.catch((error) => {
    if(error. response){
       console.log(error. response. data)
       console.log(error. response. status);

      }
})

Stephen Ostermiller on Strike's user avatar

answered Jan 14, 2021 at 5:59

Vignesh's user avatar

VigneshVignesh

1551 silver badge5 bronze badges

3

You can put the error into an object and log the object, like this:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

Stephen Ostermiller on Strike's user avatar

answered Jan 22, 2020 at 21:29

Mendy's user avatar

MendyMendy

7,4705 gold badges26 silver badges42 bronze badges

An Axios Error has a lot of information, but if you do a regular console.log(error) you would just get a ‘string message’ generic error like: «Error: Request failed with status code XXX»

A Typescript solution to handle Axios Error and other errors.

axios.get('foo.example')
    .then((response) => {//...})
    .catch (error: any) {
        let errorResponse: any;

        // it is an AxiosError
        if (error?.isAxiosError) {
            const axiosError = error as AxiosError;
            errorResponse = axiosError.response; //all the info here
        } else {
            errorResponse = error; // it is not an AxiosError
        }

        console.log(errorResponse);
        throw errorResponse;
    }

answered May 15 at 13:44

Juanma Menendez's user avatar

Juanma MenendezJuanma Menendez

16.7k7 gold badges56 silver badges55 bronze badges

It’s my code: Work for me

 var jsonData = request.body;
    var jsonParsed = JSON.parse(JSON.stringify(jsonData));

    // message_body = {
    //   "phone": "5511995001920",
    //   "body": "WhatsApp API on chat-api.com works good"
    // }

    axios.post(whatsapp_url, jsonParsed,validateStatus = true)
    .then((res) => {
      // console.log(`statusCode: ${res.statusCode}`)

            console.log(res.data)
        console.log(res.status);

        // var jsonData = res.body;
        // var jsonParsed = JSON.parse(JSON.stringify(jsonData));

        response.json("ok")
    })
    .catch((error) => {
      console.error(error)
        response.json("error")
    })

answered Jul 4, 2020 at 12:17

Rodrigo Grossi's user avatar

You can have two different ways of achieving the goal, by using the .then() and catch() method or using the async() and await() function. Let’s learn how to get the status code of an Axios HTTP Error in JavaScript.

Handling Errors With Axios

Axios is a Javascript framework that makes use of the Promise API to build HTTP requests using either XMLHttpRequests in the browser or HTTP in the Node.js runtime. These requests can use the more recent async/await syntax; the .then() utilities for promise chaining; and the .catch() mechanism for error management because they are promises.

import axios from 'axios';
try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    // Handle error
    console.log(err);
}

When performing any HTTP requests, it’s crucial to understand how to handle problems with Axios. Because there are instances when the resource you’re accessing may not be available or may return other unexpected issues. Although we’ll demonstrate the .then()/.catch() technique, async/await is the most common syntax.

Then and Catch

The async/await syntax, which we introduced above, as well as the .then() and .catch() function, are two ways that can handle promises in the current JS (). You should note that while both of these methods are capable of producing the same functionality. async/await is advantageous method because it needs less boilerplate code and can handle longer promise chains.

To accomplish the same goal using the then/catch technique, follow these steps:

import axios from 'axios';
axios.get('/my-api-route')
    .then(res => {
        // Work with the response...
    }).catch(err => {
        // Handle error
        console.log(err);
    });

Similar to the async/await syntax, the err and res are both present.

To obtain the status code from an HTTP error response, just use the status field on the error.response instance, for example, error.response.status. The status code supplied by the server in reaction to the client’s request is returned by the error.response object’s status attribute. We’ll present the .then()/.catch() technique, and also the method using await/async.

Method 1: Using .then()/.catch() function

To get the status code of the error, we caught the error in a catch block and accessed the status property on the error.response object.

Below is an illustration of how to get the status code of an Axios HTTP Error using promise.then() and promise.catch() instead of async/await.

import axios from 'axios';
axios.get('/not/exist').then((response) => {
    console.log('Working well.');
}).catch((error) => {
    if (err.response)
        console.log(err.response.status);
})

An error code 404 is expected to be returned when we sought a route that didn’t exist.

Syntax:

promise.then(success).catch(error);

Parameter:

  • success: success() function would be called on fulfillment
  • error: error() function would be called if there is a failure

Output:

404

Method 2: Using async keyword

This is how to accomplish the same goal by incorporating the async/await technique within try/catch statement:

Syntax:

async function functionname(param0) {
//  your codes
}

Parameter:

  • functionname: The name of the function.
  • param0: The parameter’s name you want to pass to the function.

For instance, you can use the following code to get the status code of an Axios HTTP Error:

async function functioname() {
  try {
  await axios.get('/not/exist');
    console.log("Working well");
  } catch (err) {
    if (err.response) {
      let statuscode = err.response.status;
      console.log(statuscode);
}
   }
}

Output:

404

Summary

We have explained how to handle errors and problems with Axios in this post and how to get the status code of an Axios HTTP error in JavaScript. This is crucial in order to avoid always delivering a general error message, giving 404 errors, or suggesting network issues to users of your application or website.

Maybe you are interested:

  • How to access the Value of a Promise in JavaScript
  • Get the Stack Trace from an Error in JavaScript
  • Get the filename without the path using JavaScript

I’m Edward Anderson. My current job is as a programmer. I’m majoring in information technology and 5 years of programming expertise. Python, C, C++, Javascript, Java, HTML, CSS, and R are my strong suits. Let me know if you have any questions about these programming languages.


Name of the university: HCMUT
Major: CS
Programming Languages: Python, C, C++, Javascript, Java, HTML, CSS, R

I have this axios code and I can’t reach response status code. What is wrong here? I get ‘undefined’ instead of 201, for example.

Thanks in advance!

  axios.post('endpoint', { body })
    .then((response) => {
        console.log(response.status);
    })

asked Apr 7, 2020 at 22:09

Robert Gurjiev's user avatar

Robert GurjievRobert Gurjiev

5001 gold badge4 silver badges17 bronze badges

2

In case of error you have to catch the result

axios.post('endpoint', { body })
    .then((response) => {
        // do something
    })
    .catch((error) => {
        console.log(error.response.status)
    })

answered Apr 7, 2020 at 23:11

Bruno Vasconcelos's user avatar

3

    post(endpoint, body) {
        return axios.post(endpoint, body)
          .then((response) => {
            return { 
               error: null, 
               data: response.data, 
               status: response.status 
             };
          })
          .catch((error) => {
            return { error: error };
      });
  }

answered Apr 8, 2020 at 8:10

Robert Gurjiev's user avatar

Robert GurjievRobert Gurjiev

5001 gold badge4 silver badges17 bronze badges

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Using the validateStatus config option, you can define HTTP code(s) that should throw an error.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Resolve only if the status code is less than 500
  }
})

Using toJSON you get an object with more information about the HTTP error.

axios.get('/user/12345')
  .catch(function (error) {
    console.log(error.toJSON());
  });

@BrunoQuaresma

I try use axios.interceptors.response and get error.config but i not found any status code or specific error message.

@AlahmadiQ8

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    console.log(error.response);
    return Promise.reject(error);
  });

hope that helps

frullah, GabeHarris, SamueleCaprioli97, beatwiz, yinjunok, RockyRx, MalgoBlock, Etheryte, vsg24, JoseWhite, and 16 more reacted with thumbs up emoji
toriiico, CristianeMayara, and mw999 reacted with hooray emoji

@BrunoQuaresma

@stevebauman

@scazzy

I tried to search SO and closed issues but couldn’t find a proper solution.
I wanted to return response.data in first param, and error.status or error.response in second param, but it didn’t work.

The error object doesn’t have any response or status. Seems it consumes output from response.data returned in the success/first param

axios.interceptors.response.use(res => response.data, function (error) {
    // Do something with response error
    console.log(error.response);
    return Promise.reject(error);
  });

@barefootChild

This problem is still there, why is closed?

@Drumstix42

Found this issue via top result on Google. Anyway, the fix for me was ensuring that I call .use on the instance of Axios that I’m using within my app.

import Axios from 'axios';

export const http = Axios.create({
    ... config ...
});

And then after:

http.interceptors.response.use(
    function(response) {
        // response data
        return response;
    },
    function(error) {
        debugger; // <-- this should now trigger correctly
        // response error
        return Promise.reject(error.response); // transform response.response -> response
    }
);

Note how I’m referencing http and not the imported Axios variable. (replace with your desired export name, etc)

@axios
axios

locked and limited conversation to collaborators

May 22, 2020

Возможно, вам также будет интересно:

  • Axie infinity ошибка 403
  • Awg 530 whirlpool коды ошибок
  • Awg 206 whirlpool ошибки
  • Awe 7527 коды ошибок
  • Awe 6514 1 whirlpool коды ошибок

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии