Last active
          July 30, 2023 17:40 
        
      - 
      
- 
        Save rchamarthi/fbb7727d0427115d39fa2e2ba5ebc680 to your computer and use it in GitHub Desktop. 
    Axios call with verifying status code and exceptions
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import axios from 'axios'; | |
| const print_response = async (url: string) => { | |
| console.log(`requesting url : ${url}`); | |
| try { | |
| const response = await axios.get(url, { | |
| validateStatus: function (status) { | |
| return status === 200; // default | |
| } | |
| }); | |
| console.log('response ' + JSON.stringify(response.status)); | |
| } catch (error) { | |
| if (axios.isAxiosError(error)) { | |
| console.log('error ' + JSON.stringify(error.name)); | |
| } else { | |
| console.log('unexpected error ' + JSON.stringify(error)); | |
| } | |
| } | |
| } | |
| print_response('https://httpstat.us/204'); | |
| ``` | |
| # output | |
| ``` | |
| requesting url : https: //httpstat.us/204 | |
| error | |
| { | |
| "message": "Request failed with status code 204", | |
| "name": "AxiosError", | |
| "stack": "AxiosError: Request failed with status code 204\n at settle (/Users/rajeshch/repos/axios-test/node_modules/axios/lib/core/settle.js:19:12)\n at IncomingMessage.handleStreamEnd (/Users/rajeshch/repos/axios-test/node_modules/axios/lib/adapters/http.js:570:11)\n at IncomingMessage.emit (node:events:525:35)\n at IncomingMessage.emit (node:domain:489:12)\n at endReadableNT (node:internal/streams/readable:1358:12)\n at processTicksAndRejections (node:internal/process/task_queues:83:21)", | |
| "config": { | |
| "transitional": { | |
| "silentJSONParsing": true, | |
| "forcedJSONParsing": true, | |
| "clarifyTimeoutError": false | |
| }, | |
| "adapter": [ | |
| "xhr", | |
| "http" | |
| ], | |
| "transformRequest": [ | |
| null | |
| ], | |
| "transformResponse": [ | |
| null | |
| ], | |
| "timeout": 0, | |
| "xsrfCookieName": "XSRF-TOKEN", | |
| "xsrfHeaderName": "X-XSRF-TOKEN", | |
| "maxContentLength": -1, | |
| "maxBodyLength": -1, | |
| "env": { | |
| "Blob": null | |
| }, | |
| "headers": { | |
| "Accept": "application/json, text/plain, */*", | |
| "User-Agent": "axios/1.4.0", | |
| "Accept-Encoding": "gzip, compress, deflate, br" | |
| }, | |
| "method": "get", | |
| "url": "https://httpstat.us/204" | |
| }, | |
| "status": 204 | |
| } | |
| ``` | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment