PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to read error object of exception thrown by Axios

 October 13, 2022     axios, javascript     No comments   

Issue

Error object is received in exception of a try catch block that calls axios function. console.log of error appears like this:

[AxiosError: Request failed with status code 404] {
  code: 'ERR_BAD_REQUEST',
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function] },
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded',
      cookie: 'JSESSIONID=undefined;',
      'User-Agent': 'axios/0.27.2'
    },
    method: 'post',
    url: 'https://myserver.url/myapifunction',
    data: undefined
  },

There are many more lines further in this.

Questions:

  1. This is not perfect JSON. How to read this?
  2. In case of success (no exception), it is perfect JSON I get, having one of keys status. So in calling function I am just doing returnValue.status to know status code of Axios call. But in case of failure this whole object doesn't hold status key. How to handle this?

Solution

Ok I resolved this.

Line in try catch block

let promiseRet = await new Promise (function( resolve, reject); 

In case of success:

return promiseRet.status;

In case of exception:

const errResp = Object.assign({},err).response;
return errResp.status;


Answered By - Atul
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing