Skip to content

Commit 04929c6

Browse files
committed
Add Get The Response Status From An Axios Error as a javascript til
1 parent 39744a0 commit 04929c6

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1128 TILs and counting..._
13+
_1129 TILs and counting..._
1414

1515
---
1616

@@ -385,6 +385,7 @@ _1128 TILs and counting..._
385385
- [Freeze An Object, Sorta](javascript/freeze-an-object-sorta.md)
386386
- [Generate Random Integers](javascript/generate-random-integers.md)
387387
- [Get The Location And Size Of An Element](javascript/get-the-location-and-size-of-an-element.md)
388+
- [Get The Response Status From An Axios Error](javascript/get-the-response-status-from-an-axios-error.md)
388389
- [Get The Time Zone Of The Client Computer](javascript/get-the-time-zone-of-the-client-computer.md)
389390
- [Globally Install A Package With Yarn](javascript/globally-install-a-package-with-yarn.md)
390391
- [Immutable Remove With The Spread Operator](javascript/immutable-remove-with-the-spread-operator.md)
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Get The Response Status From An Axios Error
2+
3+
You can make API requests with [`axios`](https://github.com/axios/axios). If
4+
the request fails because of a 4xx or 5xx response, an error will be raised.
5+
The response to the request is stored on the error so that you can still access
6+
the details of the response in your error handling logic.
7+
8+
Here is a snippet of code that details using async/await with `axios`. It wraps
9+
the call in a `try/catch` block.
10+
11+
```javascript
12+
async function getCharacter(characterId) {
13+
let response;
14+
15+
try {
16+
response = await axios.get(
17+
`https://rickandmortyapi.com/api/character/${characterId}`
18+
);
19+
} catch (e) {
20+
response = e.response;
21+
}
22+
23+
console.log(response.status);
24+
25+
// You can also access the response data
26+
// console.log(response.data);
27+
}
28+
29+
getCharacter(2);
30+
//=> 200
31+
32+
getCharacter(2000);
33+
//=> 404
34+
```
35+
36+
In the case of the second call that results in a 404 response, the `catch`
37+
block is executed. This pulls the `response` off the error (`e`).
38+
39+
Just like the standard response, the response from the error contains `status`,
40+
`data`, `headers`, etc.
41+
42+
This also works with a promise-based control flow.
43+
44+
[Live Example](https://codesandbox.io/s/ancient-currying-5cmgm?file=/src/index.js)

0 commit comments

Comments
 (0)