forked from HackYourFuture/JavaScript3_examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
33 lines (30 loc) · 723 Bytes
/
Copy pathapp.js
File metadata and controls
33 lines (30 loc) · 723 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
Add error handling using a node-style callback.
Handle:
1. HTTP errors
2. Network errors
*/
'use strict';
{
function fetchJSON(url, cb) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open('GET', url);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status <= 299) {
cb(null, xhr.response);
} else {
cb(new Error(`Network error: ${xhr.status} - ${xhr.statusText}`));
}
};
xhr.onerror = () => cb(new Error('Network request failed'));
xhr.send();
}
fetchJSON('http://api.nobelprize.org/v1/country.json', (err, data) => {
if (err) {
console.error(err.message);
} else {
console.log(data);
}
});
}