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?