You just need try/catch
around your await
as that's how you catch promise rejections when using await
.
try {
let user = await axios.get(`${base_api_url}/users/${req.params.username}`, options)
let events = await axios.get(`${base_api_url}/users/${req.params.username}/events`, options)
res.json({
success:true,
user: user.data,
events: events.data
})
} catch(e) {
console.log(e);
// decide what to do here when you get an error
res.status(500).send("axios error")'
}
Run Requests In Parallel
FYI, you don't need to sequence your two axios calls one after the other. You could likely speed things up a bit with Promise.all()
:
Promise.all([
axios.get(`${base_api_url}/users/${req.params.username}`, options),
axios.get(`${base_api_url}/users/${req.params.username}/events`, options)
]).then(([user, events]) => {
res.json({
success:true,
user: user.data,
events: events.data
});
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
or:
try {
let [user, events] = await Promise.all([
axios.get(`${base_api_url}/users/${req.params.username}`, options),
axios.get(`${base_api_url}/users/${req.params.username}/events`, options)
]);
res.json({
success:true,
user: user.data,
events: events.data
} catch(err) {
console.log(err);
res.sendStatus(500);
}