From 04929c65f3ba23c30f989443aff1ec78fb074c20 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 6 Jun 2021 13:52:36 -0500 Subject: [PATCH] Add Get The Response Status From An Axios Error as a javascript til --- README.md | 3 +- ...the-response-status-from-an-axios-error.md | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 javascript/get-the-response-status-from-an-axios-error.md diff --git a/README.md b/README.md index be8d0e6..6147796 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/javascript/get-the-response-status-from-an-axios-error.md b/javascript/get-the-response-status-from-an-axios-error.md new file mode 100644 index 0000000..e574eb0 --- /dev/null +++ b/javascript/get-the-response-status-from-an-axios-error.md @@ -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)