I am making a request to an API that gives me some basic account details.
If anything fails connecting to the endpoint, the try catch
works correctly and it executes the catch
block.
But I want to throw
an error depending on the data I am getting, but it defaults to the catch
block. How can I do this?
Here is a mockup of what I am trying to achieve.
import axios from 'axios'
export default async () => {
try {
const { data } = await axios('https://api.endpoint.com')
if (data.credits < 10) {
throw 'No enough credits'
} else {
return 'All good'
}
} catch (error) {
throw 'Error connecting...'
}
}
CodePudding user response:
Try this
import axios from 'axios'
export default async() => {
try {
const { data } = await axios('https://api.endpoint.com')
if (data.credits < 10) {
// !important! throw a string, not a new Error
// since axios won't throw a string
throw 'No enough credits';
} else {
return 'All good'
}
} catch (error) {
if (typeof error === "string") throw error;
throw 'Error connecting...'
}
}
CodePudding user response:
You are not doing anything with the caught error, if you want to handle the error in the catch block, don't throw a new error.
This code will always throw catch
try {
throw "not enough credits";
} catch (e) {
throw "catch";
}
Instead you could for example handle it.
try {
throw "not enough credits";
} catch (e) {
console.log(e); // handle the error in some way
}
Rethrowing the caught error just does the same thing as throwing in the first place.
try {
throw "not enough credits";
} catch (e) {
throw e;
}
So is basically the same thing as doing this.
throw "not enough credits";
You could throw a new error with some extra data from the caught error.
try {
throw "not enough credits";
} catch (e) {
throw `something went wrong: ${e}`;
}
So in your example, you could do something like this.
import axios from 'axios'
export default async () => {
try {
const { data } = await axios('https://api.endpoint.com')
if (data.credits < 10) {
throw 'not enough credits'
} else {
return 'All good'
}
} catch (error) {
throw `Error connecting... ${error}`
}
}
But I would prefer doing something like this.
const getData = () => {
const data = { credits: 5 };
if (data.credits < 10) {
throw 'not enough credits'
} else {
return 'All good'
}
}
// call the function and handle the error on another level
try {
const data = getData();
// do something with data
} catch (e) {
console.log(`fetching data failed: ${e}`);
}