-
SummaryI want to handle the unhandled runtime errors that says [ Server ] Error: fetch failed. Because, when I was reading the docs about the error handling, the throw doesn't work and basic return like return 'Error when fetching data X' too. It always return the same message [ Server ] Error: fetch failed, not the custom one Additional informationmy code are something like this
export default async function Home() {
const token = await getAccessToken();
const response = await fetch('https://localhost:8000/v1/products');
if (!response.ok) {
throw new Error('Failed to fetch products');
}
const products = response.json();
const products: Products[] = products.data; ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hiya! This is because the export default async function Home() {
let products: Products[];
try {
const token = await getAccessToken();
const response = await fetch('https://localhost:8000/v1/products');
if (!response.ok) {
throw new Error(response.statusText);
}
const products = response.json();
products = products.data;
}
catch (e) {
console.error(`Failed to fetch products: ${e}`);
}
if (!products.length) {
// Some error handling here, like `notFound()`.
}
// The rest of the code.
} |
Beta Was this translation helpful? Give feedback.
Hiya!
This is because the
fetch
function throws when it cannot get a response. Theresponse.ok
check is correct, but is only used to check if the response has a2XX
HTTP status code.The following example should work for you: