Reputation: 4759
In below async Javascript function (which I use server side in Node js), I am doing a Graphql request using fetch
api:
import GET_DATA from './getData.gql';
const getData = async (url: string) => {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: GET_DATA,
variables: {
url,
},
}),
};
const response = await fetch(process.env.ENDPOINT, options);
if (!response.ok) {
throw new Error('Unable to parse');
}
const result = await response.json();
if (result.errors?.length) {
throw new Error(
'An error occurred',
result.errors.map((e: Error) => e.message)
);
}
return result.data.page;
};
export default getData;
What is better here to catch the errors using try catch
or like I do now throw new Error
and what is exactly the difference? Maybe I can improve above function to handle and print the errors?
Upvotes: 0
Views: 619
Reputation: 33
n your current implementation, you are throwing an error if the response is not OK or if there are any errors in the result. When an error is thrown, it stops the execution of the code and jumps to the nearest catch block (if any) or to the global error handler (if there is none).
If you use try-catch block, you can handle the error in a more controlled way, rather than completely stopping the execution of the code. You can catch the error and handle it gracefully by providing a fallback or retry mechanism.
using try-catch block is a better approach for error handling than throwing new Error directly because it allows you to handle errors more gracefully and in a more controlled way.
Upvotes: 0