How to code error messages?

The weather API was down for a bit, so my site wouldn’t load. How do I code an error message into my script to display something like “error 503, the weather data is unreachable” just in case it happens again?

Thank you.

The exact way completely depends on what you’re using to make the request (XMLHttpRequest, some library like jQuery, fetch). But all methods will return a response with a header that contains the HTTP status code. When you get the response, you check what the status code is, and if it’s bad news bears, act accordingly. Otherwise you carry on & render the data

So like

async function getWeather() {
  const request = await fetch(theUrlForTheRequestHere);
  if (request.ok) {
    const data = await request.json();
    // do something with the data
  } else if (request.status === 503) {
    // do something special if the server is down
  } else {
    // This is a catch-all, something has gone wrong!
    // i.e. the reponse status is not in the range 200-299.
    // Do something else

Thank you so much for your reply! I will try that