mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Get The Response Status From An Axios Error as a javascript til
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||
|
||||
_1128 TILs and counting..._
|
||||
_1129 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -385,6 +385,7 @@ _1128 TILs and counting..._
|
||||
- [Freeze An Object, Sorta](javascript/freeze-an-object-sorta.md)
|
||||
- [Generate Random Integers](javascript/generate-random-integers.md)
|
||||
- [Get The Location And Size Of An Element](javascript/get-the-location-and-size-of-an-element.md)
|
||||
- [Get The Response Status From An Axios Error](javascript/get-the-response-status-from-an-axios-error.md)
|
||||
- [Get The Time Zone Of The Client Computer](javascript/get-the-time-zone-of-the-client-computer.md)
|
||||
- [Globally Install A Package With Yarn](javascript/globally-install-a-package-with-yarn.md)
|
||||
- [Immutable Remove With The Spread Operator](javascript/immutable-remove-with-the-spread-operator.md)
|
||||
|
||||
44
javascript/get-the-response-status-from-an-axios-error.md
Normal file
44
javascript/get-the-response-status-from-an-axios-error.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# Get The Response Status From An Axios Error
|
||||
|
||||
You can make API requests with [`axios`](https://github.com/axios/axios). If
|
||||
the request fails because of a 4xx or 5xx response, an error will be raised.
|
||||
The response to the request is stored on the error so that you can still access
|
||||
the details of the response in your error handling logic.
|
||||
|
||||
Here is a snippet of code that details using async/await with `axios`. It wraps
|
||||
the call in a `try/catch` block.
|
||||
|
||||
```javascript
|
||||
async function getCharacter(characterId) {
|
||||
let response;
|
||||
|
||||
try {
|
||||
response = await axios.get(
|
||||
`https://rickandmortyapi.com/api/character/${characterId}`
|
||||
);
|
||||
} catch (e) {
|
||||
response = e.response;
|
||||
}
|
||||
|
||||
console.log(response.status);
|
||||
|
||||
// You can also access the response data
|
||||
// console.log(response.data);
|
||||
}
|
||||
|
||||
getCharacter(2);
|
||||
//=> 200
|
||||
|
||||
getCharacter(2000);
|
||||
//=> 404
|
||||
```
|
||||
|
||||
In the case of the second call that results in a 404 response, the `catch`
|
||||
block is executed. This pulls the `response` off the error (`e`).
|
||||
|
||||
Just like the standard response, the response from the error contains `status`,
|
||||
`data`, `headers`, etc.
|
||||
|
||||
This also works with a promise-based control flow.
|
||||
|
||||
[Live Example](https://codesandbox.io/s/ancient-currying-5cmgm?file=/src/index.js)
|
||||
Reference in New Issue
Block a user