-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Labels
Description
Line 3 in 55aa475
const fetch = function (url, callback) { |
This is fine, but you've hardcoded specific error handling actions inside this function:
Lines 9 to 23 in 55aa475
} else if (xhr.readyState === 4 && xhr.status === 500) { | |
const main = document.querySelector('.main'); | |
const alertHead = document.createElement('h1'); | |
const alertText = document.createTextNode('Oopsy doodle, there has been a problem'); | |
const bod = document.querySelector('.body'); | |
while (alert.firstChild) { | |
alert.removeChild(alert.firstChild); | |
} | |
alertHead.appendChild(alertText); | |
alert.appendChild(alertHead); | |
} else { | |
console.log('XHR error', xhr.readyState); | |
} |
For a larger app, it makes sense to make this function more general (and therefore more versatile), by allowing some arbitrary function to be executed in the case of an error (just like you're doing in the case of a successful response). There's two ways you can do this:
- Accept a second callback argument in
fetch
.
const fetch = (url, successCallback, failureCallback) => {
// ...
if (/* successful request */) {
successCallback(/* data */)
} else {
failureCallback(/* error message? */)
}
}
- Use the error-first callback pattern:
const fetch = (url, callback) => {
// ...
if (/* successful request */) {
callback(null, /* data */)
} else {
callback(/* error message? */)
}
}