Here’s my chunk of code:
const getToken = async () => {
try {
const token = await axios.post(keys.sessionURL, {
email: keys.verificationEmail,
password: keys.verificationPassword,
});
} catch (err) {
throw new Error('Unable to establish a login session.'); // here I'd like to send the error to the user instead
}
};
So as you can see I’m connecting to external server in order to get a token. And that works. Now, I’d like to catch an error but this time not with ‘throw new error’ but I’d like to send it to the user, so I’d like to have something like this instead:
res.status(401).send('Unable to get a token');
But because I’m not inside the route handler I cannot use ‘res’. How can I send it to the user then?
Thank you!
asked Sep 26, 2018 at 7:17
1
For axios version-0.19.0 below code worked after hours of struggling with async await.Not sure about other versions though!
catch(error){
console.log(error.response.data.error)
}
user
5,2976 gold badges19 silver badges35 bronze badges
answered Jun 19, 2020 at 14:44
Akshay SethAkshay Seth
1,1741 gold badge11 silver badges11 bronze badges
2
You can keep almost the same function
const getToken = async () => {
try {
const token = await axios.post(keys.sessionURL, {
email: keys.verificationEmail,
password: keys.verificationPassword,
})
} catch (err) {
throw new Error('Unable to get a token.')
}
}
Then from your route handler just catch
the eventual exception
app.get('/endpoint', async (req, res) => {
try {
const token = await getToken()
// Do your stuff with the token
// ...
} catch (err) {
// Error handling here
return res.status(401).send(err.message);
}
})
The default js exception system works well to pass error data through the call stack.
its4zahoor
1,5991 gold badge15 silver badges21 bronze badges
answered Sep 26, 2018 at 7:49
MaximeMaxime
3952 silver badges9 bronze badges
In my solution I use:
try{
let responseData = await axios.get(this.apiBookGetBookPages + bookId, headers);
console.log(responseData);
}catch(error){
console.log(Object.keys(error), error.message);
}
If something failed we will get en error like this:
[ 'config', 'request', 'response', 'isAxiosError', 'toJSON' ]
'Request failed with status code 401'
We can also get status code:
...
}catch(error){
if(error.response && error.response.status == 401){
console.log('Token not valid!');
}
}
answered May 19, 2020 at 8:10
Lev K.Lev K.
3444 silver badges4 bronze badges
you keep a flag like isAuthError
and if error occurs send it as true and in the main function if the flag isAuthError
is true throw the err and handle in catch otherwise perform your operations. I’ve added an example below. hope it helps
const getToken = async () => {
try {
const token = await axios.post(keys.sessionURL, {
email: keys.verificationEmail,
password: keys.verificationPassword,
});
return {token, isAuthError: false};
} catch (err) {
// throw new Error('Unable to establish a login session.'); // here I'd like to send the error to the user instead
return {err, isAuthError: true};
}
};
mainFunction
app.post('/login', async (req, res)=>{
try{
// some validations
let data = await getToken();
if( data.isAuthError){
throw data.err;
}
let token = data.token;
//do further required operations
}catch(err){
//handle your error here with whatever status you need
return res.status(500).send(err);
}
})
answered Sep 26, 2018 at 7:42
Atishay JainAtishay Jain
1,39512 silver badges22 bronze badges
1
try/catch is not a good solution. It’s meant to catch runtime error, not HTTP error coming from axios if error is processed by interceptor and then passed back to caller via return Promise.reject(error);
here is interceptor example
axios.interceptors.response.use(
response => {
//maybe process here
return response;
},
error => {
//do some global magic with error and pass back to caller
return Promise.reject(error);
}
);
Let’s start with try/catch example that won’t work
for(let i=0; i<5;i++) {
try{
const result = async axios.get(`${/item/{i}}`);
}
catch(error) {
//error undefined here, you would expect an error from pattern like axios.get(...).then(...).catch(real_http_error)
}
}
I found this pattern to work. Let say you want to make calls in a loop to make avoid multiple http call due to async nature of JS.
for(let i=0; i<5;i++) {
const result = async axios.get(`${/item/{i}}`).catch(error) { //chain catch despite async keyword
//now you access http error and you can do something with it
//but calling break; or return; won't break for loop because you are in a callback
}
if(!result) { //due to http error
continute; //keep looping for next call
//or break; to stop processing after 1st error
}
//process response here, result.data...
}
answered Aug 26, 2021 at 18:56
Pawel CiochPawel Cioch
2,7511 gold badge28 silver badges29 bronze badges
1
Keep the grace of async / await
:
const result = await axios.post('/url', params)
.catch((err) => {
// deal with err, such as toggle loading state, recover click and scroll.
this.loading = false;
// recover the reject state before.
return Promise.reject(err);
});
this.data = result; // not exec when reject
answered Dec 23, 2021 at 4:30
DreamoonDreamoon
3393 silver badges8 bronze badges
Elegant & with TypeScript.
import axios, { AxiosResponse, AxiosError } from "axios";
...
const response: void | AxiosResponse<any, any> = await axios({
headers: {
Authorization: `Bearer ${XYZ}`,
Accept: "application/json",
},
method: "GET",
params: {
...
},
url: "https://api.abcd.com/...",
}).catch((error: AxiosError) => {
if (error instanceof Error) {
console.error(
"Error with fetching ..., details: ",
error
);
}
});
answered Feb 7, 2022 at 8:31
const getPass = (e) => {
e.preventDefault()
const post = { userName: userName }
axios.post("/", post) //axios.post(keys.sessionURL, {email: keys.verificationEmail,password: keys.verificationPassword,})
.then(res => {
if(!res.ok){
throw Error('Network Error'); //error from axios
}
return res.json();
}).catch(err => {
console.log(err.message) //to display the error to your user just use the useState to define your error
})
}
const getPass = (e) => {
e.preventDefault()
const post = { userName: userName }
axios.post("/", post) //axios.post(keys.sessionURL, {email: keys.verificationEmail,password: keys.verificationPassword,})
.then(res => {
if(!res.ok){
throw Error('Network Error'); //error from axios
}
return res.json();
}).catch(err => {
console.log(err.message) //to display the error to your user just use the useState to define your error
})
}
answered Jan 18 at 0:20
1
Here’s my chunk of code:
const getToken = async () => {
try {
const token = await axios.post(keys.sessionURL, {
email: keys.verificationEmail,
password: keys.verificationPassword,
});
} catch (err) {
throw new Error('Unable to establish a login session.'); // here I'd like to send the error to the user instead
}
};
So as you can see I’m connecting to external server in order to get a token. And that works. Now, I’d like to catch an error but this time not with ‘throw new error’ but I’d like to send it to the user, so I’d like to have something like this instead:
res.status(401).send('Unable to get a token');
But because I’m not inside the route handler I cannot use ‘res’. How can I send it to the user then?
Thank you!
asked Sep 26, 2018 at 7:17
1
For axios version-0.19.0 below code worked after hours of struggling with async await.Not sure about other versions though!
catch(error){
console.log(error.response.data.error)
}
user
5,2976 gold badges19 silver badges35 bronze badges
answered Jun 19, 2020 at 14:44
Akshay SethAkshay Seth
1,1741 gold badge11 silver badges11 bronze badges
2
You can keep almost the same function
const getToken = async () => {
try {
const token = await axios.post(keys.sessionURL, {
email: keys.verificationEmail,
password: keys.verificationPassword,
})
} catch (err) {
throw new Error('Unable to get a token.')
}
}
Then from your route handler just catch
the eventual exception
app.get('/endpoint', async (req, res) => {
try {
const token = await getToken()
// Do your stuff with the token
// ...
} catch (err) {
// Error handling here
return res.status(401).send(err.message);
}
})
The default js exception system works well to pass error data through the call stack.
its4zahoor
1,5991 gold badge15 silver badges21 bronze badges
answered Sep 26, 2018 at 7:49
MaximeMaxime
3952 silver badges9 bronze badges
In my solution I use:
try{
let responseData = await axios.get(this.apiBookGetBookPages + bookId, headers);
console.log(responseData);
}catch(error){
console.log(Object.keys(error), error.message);
}
If something failed we will get en error like this:
[ 'config', 'request', 'response', 'isAxiosError', 'toJSON' ]
'Request failed with status code 401'
We can also get status code:
...
}catch(error){
if(error.response && error.response.status == 401){
console.log('Token not valid!');
}
}
answered May 19, 2020 at 8:10
Lev K.Lev K.
3444 silver badges4 bronze badges
you keep a flag like isAuthError
and if error occurs send it as true and in the main function if the flag isAuthError
is true throw the err and handle in catch otherwise perform your operations. I’ve added an example below. hope it helps
const getToken = async () => {
try {
const token = await axios.post(keys.sessionURL, {
email: keys.verificationEmail,
password: keys.verificationPassword,
});
return {token, isAuthError: false};
} catch (err) {
// throw new Error('Unable to establish a login session.'); // here I'd like to send the error to the user instead
return {err, isAuthError: true};
}
};
mainFunction
app.post('/login', async (req, res)=>{
try{
// some validations
let data = await getToken();
if( data.isAuthError){
throw data.err;
}
let token = data.token;
//do further required operations
}catch(err){
//handle your error here with whatever status you need
return res.status(500).send(err);
}
})
answered Sep 26, 2018 at 7:42
Atishay JainAtishay Jain
1,39512 silver badges22 bronze badges
1
try/catch is not a good solution. It’s meant to catch runtime error, not HTTP error coming from axios if error is processed by interceptor and then passed back to caller via return Promise.reject(error);
here is interceptor example
axios.interceptors.response.use(
response => {
//maybe process here
return response;
},
error => {
//do some global magic with error and pass back to caller
return Promise.reject(error);
}
);
Let’s start with try/catch example that won’t work
for(let i=0; i<5;i++) {
try{
const result = async axios.get(`${/item/{i}}`);
}
catch(error) {
//error undefined here, you would expect an error from pattern like axios.get(...).then(...).catch(real_http_error)
}
}
I found this pattern to work. Let say you want to make calls in a loop to make avoid multiple http call due to async nature of JS.
for(let i=0; i<5;i++) {
const result = async axios.get(`${/item/{i}}`).catch(error) { //chain catch despite async keyword
//now you access http error and you can do something with it
//but calling break; or return; won't break for loop because you are in a callback
}
if(!result) { //due to http error
continute; //keep looping for next call
//or break; to stop processing after 1st error
}
//process response here, result.data...
}
answered Aug 26, 2021 at 18:56
Pawel CiochPawel Cioch
2,7511 gold badge28 silver badges29 bronze badges
1
Keep the grace of async / await
:
const result = await axios.post('/url', params)
.catch((err) => {
// deal with err, such as toggle loading state, recover click and scroll.
this.loading = false;
// recover the reject state before.
return Promise.reject(err);
});
this.data = result; // not exec when reject
answered Dec 23, 2021 at 4:30
DreamoonDreamoon
3393 silver badges8 bronze badges
Elegant & with TypeScript.
import axios, { AxiosResponse, AxiosError } from "axios";
...
const response: void | AxiosResponse<any, any> = await axios({
headers: {
Authorization: `Bearer ${XYZ}`,
Accept: "application/json",
},
method: "GET",
params: {
...
},
url: "https://api.abcd.com/...",
}).catch((error: AxiosError) => {
if (error instanceof Error) {
console.error(
"Error with fetching ..., details: ",
error
);
}
});
answered Feb 7, 2022 at 8:31
const getPass = (e) => {
e.preventDefault()
const post = { userName: userName }
axios.post("/", post) //axios.post(keys.sessionURL, {email: keys.verificationEmail,password: keys.verificationPassword,})
.then(res => {
if(!res.ok){
throw Error('Network Error'); //error from axios
}
return res.json();
}).catch(err => {
console.log(err.message) //to display the error to your user just use the useState to define your error
})
}
const getPass = (e) => {
e.preventDefault()
const post = { userName: userName }
axios.post("/", post) //axios.post(keys.sessionURL, {email: keys.verificationEmail,password: keys.verificationPassword,})
.then(res => {
if(!res.ok){
throw Error('Network Error'); //error from axios
}
return res.json();
}).catch(err => {
console.log(err.message) //to display the error to your user just use the useState to define your error
})
}
answered Jan 18 at 0:20
1
Axios is a popular JavaScript library for making HTTP requests. It is promise-based, and makes it easy to work with asynchronous requests in your applications. In this tutorial, we will go over some of the best practices for using Axios to make HTTP requests.
Installing Axios
To use Axios in your project, you will first need to install it. You can do this using either npm or yarn.
npm
To install Axios using npm, run the following command in your terminal:
npm install axios
Enter fullscreen mode
Exit fullscreen mode
yarn
To install Axios using yarn, run the following command in your terminal:
yarn add axios
Enter fullscreen mode
Exit fullscreen mode
Making Requests
Once you have Axios installed, you can start making HTTP requests. Here is an example of a simple GET request:
axios.get('/api/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Enter fullscreen mode
Exit fullscreen mode
In this example, we are making a GET request to the /api/users
endpoint. If the request is successful, the response data will be logged to the console. If there is an error, it will be caught and logged to the console.
You can also make POST requests using Axios. Here is an example of a POST request:
axios.post('/api/users', {
name: 'John Smith',
email: 'john@example.com'
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Enter fullscreen mode
Exit fullscreen mode
In this example, we are making a POST request to the /api/users
endpoint with a payload containing a name and email.
Customizing Requests
You can customize your Axios requests by passing in additional options as an object. For example, you can pass in headers, params, and other options.
axios.get('/api/users', {
headers: {
'Authorization': 'Bearer abc123'
},
params: {
page: 2
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Enter fullscreen mode
Exit fullscreen mode
In this example, we are passing in an Authorization
header with a bearer token, and a page
param with a value of 2
.
Working with Promises
Axios uses Promises to handle asynchronous requests. This means that you can use the then
and catch
methods to handle success and error cases.
axios.get('/api/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Enter fullscreen mode
Exit fullscreen mode
In this example, we are making a GET request to the /api/users
endpoint. If the request is successful, the response data will be logged to the console. If there is an error, it will also be logged to the console.
Error Handling
It’s important to handle errors properly in your Axios requests. You can do this using the catch
method, as shown in the previous examples. You can also use the catch
method to handle specific errors. For example, you might want to handle a 404
error differently than a 500
error.
axios.get('/api/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
Enter fullscreen mode
Exit fullscreen mode
In this example, we are using the error.response
object to log the data, status code, and headers of the response. We are also logging the error.request
object, which is the request that was made. Finally, we are logging the error.config
object, which contains the config that was used to make the request.
Setting Default Options
You can set default options for all of your Axios requests by creating an instance of the Axios library with the default options.
const axios = require('axios');
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000,
headers: {
'Authorization': 'Bearer abc123'
}
});
instance.get('/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Enter fullscreen mode
Exit fullscreen mode
In this example, we are creating an instance of Axios with a base URL of https://api.example.com
, a timeout of 1000
milliseconds, and an Authorization
header with a bearer token. Any requests made with this instance will have these default options applied.
Cancelling Requests
You can cancel an Axios request by using the CancelToken
object. This is useful if you need to cancel a request that is taking too long, or if you no longer need the response of a request.
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/api/users', {
cancelToken: source.token
})
.then(response => {
console.log(response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('Request cancelled', error.message);
} else {
console.log(error);
}
});
// cancel the request (the message parameter is optional)
source.cancel('Operation cancelled by the user.');
Enter fullscreen mode
Exit fullscreen mode
In this example, we are creating a CancelToken
object and a source
object. We are then passing the source.token
to the cancelToken
option of the Axios request. To cancel the request, we call the cancel
method on the source
object. The isCancel
method is used to check if the error is a cancellation error.
Using Axios with Async/Await
You can use Axios with async/await to make your code more readable and easier to work with. Here is an example of an async function that makes an Axios request:
async function getUsers() {
try {
const response = await axios.get('/api/users');
console.log(response.data);
} catch (error) {
console.log(error);
}
}
getUsers();
Enter fullscreen mode
Exit fullscreen mode
In this example, we are using the await
keyword to wait for the Axios request to resolve before logging the response data to the console. If there is an error, it will be caught and logged to the console.
Conclusion
In this tutorial, we went over some of the best practices for using Axios to make HTTP requests. We covered how to install Axios, make requests, customize requests, handle errors, set default options, cancel requests, and use async/await. With these skills, you should be well on your way to using Axios effectively in your projects.