To return a 404 page when the API response indicates that the team was not found, you can use Astro's Response object to set the appropriate status code and then use Astro.redirect() to redirect to your custom 404 page. Here's how you can modify your code to achieve this:
---
try {
const newNumber = parseInt(name!);
let response;
if (Number.isNaN(newNumber)) {
response = await fetch(`<https://api.first2challenger.es/teams/name/${name}`>);
} else {
response = await fetch(`<https://api.first2challenger.es/teams/${name}`>);
}
if (!response.ok) {
throw new Error(`Failed to fetch team data: ${response.status}`);
}
const data = await response.json();
if (data.result === "Equipo no encontrado.") {
return new Response(null, {
status: 404,
statusText: 'Not found'
});
}
team = data.result;
} catch (error) {
console.error("Error fetching team data:", error);
return new Response(null, {
status: 404,
statusText: 'Not found'
});
}
---
<!-- Rest of your component code -->
In this modified code, we check if the data.result is "Equipo no encontrado." (Team not found). If it is, we return a new Response object with a 404 status code. We do the same thing in the catch block to handle any other errors that might occur during the fetch operation.
To make this work, you need to ensure you have a custom 404 page set up in your Astro project. You can create a custom 404 page by adding a 404.astro or 404.md file in your src/pages/ directory as described in the Astro documentation on custom 404 error pages.
For example, you could create a file src/pages/404.astro with content like this: