In
.catch(err => {
app.innerHTML = notFound
console.log('error: ' + err)
});
you don't actually know whether the issue is a 404 or something completely different. For example, if you access your article.html
like this:
file:///C:/dev/plain-javascript-tutorial/article.html#smudla
The console shows this message:
error: TypeError: Cannot read property 'teaser_image' of undefined
This doesn't seem right as it happens because in
.then(response => {
var article = response.items[0];
let headerImage = document.createElement("img");
headerImage.setAttribute("class", "article-header");
headerImage.src = article.teaser_image.value[0].url + "?w=500&h=500";
let title = document.createElement("h2");
title.setAttribute("class", "article-title");
title.innerText = article.title.value;
let body = document.createElement("div");
body.setAttribute("class", "article-description");
body.innerHTML = article.body_copy.resolveHtml();
articleContainer.appendChild(headerImage);
articleContainer.appendChild(title);
articleContainer.appendChild(body);
})
You don't verify if article was found or not. You could use something like this:
.then(response => {
const article = response.items.length ? response.items[0] : undefined;
if (!article) {
app.innerHTML = notFound
return;
}
let headerImage = document.createElement("img");
headerImage.setAttribute("class", "article-header");
headerImage.src = article.teaser_image.value[0].url + "?w=500&h=500";
let title = document.createElement("h2");
title.setAttribute("class", "article-title");
title.innerText = article.title.value;
let body = document.createElement("div");
body.setAttribute("class", "article-description");
body.innerHTML = article.body_copy.resolveHtml();
articleContainer.appendChild(headerImage);
articleContainer.appendChild(title);
articleContainer.appendChild(body);
})
The catch could look as simple as:
.catch(err => {
console.error(err);
app.innerHTML = `I'm unknown error :(`;
});
There is a way to handle cloud specific errors, but that doesn't currently work in plain js without explicitely referencing kentico-cloud-core
package. I'll have to move objects around to make it work as explained here (https://github.com/Kentico/kentico-cloud-js/blob/master/packages/delivery/DOCS.md#handling-errors)
use
console.error('error...');