Skip to content

Commit 47e4bf6

Browse files
committed
replaced hardcoded URL with constant and improved error handling with defensive coding
1 parent 693adcf commit 47e4bf6

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

fetch/programmer-humour/script.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1+
const API_URL = "https://xkcd.now.sh/?comic=latest";
2+
13
async function getLatestComic() {
2-
const url = "https://xkcd.now.sh/?comic=latest";
34
const container = document.getElementById("comic-container");
45

56
try {
6-
const response = await fetch(url);
7+
const response = await fetch(API_URL);
78

89
if (!response.ok) {
910
throw new Error(`HTTP error: ${response.status}`);
@@ -12,16 +13,20 @@ async function getLatestComic() {
1213
const data = await response.json();
1314
console.log(data);
1415

16+
if (!data.img) {
17+
throw new Error("API did not return an image");
18+
}
19+
1520
container.innerHTML = "";
1621

1722
const img = document.createElement("img");
1823
img.src = data.img;
19-
img.alt = data.title;
24+
img.alt = data.alt || data.title || "XKCD comic";
2025

2126
container.appendChild(img);
2227
} catch (error) {
2328
console.error("Fetch error:", error);
24-
container.innerHTML = `<p>Something went wrong loading the comic.</p>`;
29+
container.innerHTML = `<p>Could not load the comic. Please try again later.</p>`;
2530
}
2631
}
2732

0 commit comments

Comments
 (0)