-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample1.js
More file actions
72 lines (63 loc) · 1.43 KB
/
Copy pathexample1.js
File metadata and controls
72 lines (63 loc) · 1.43 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Example 1
let json = '{"age": 30 }';
let user = JSON.parse(json);
try {
if (!user.name) {
throw new SyntaxError("Incomplete data: no name");
}
} catch (e) {
console.log("JSON Error: " + e.message);
}
console.log("\n");
// Example 2
try {
let username = "mbrsagor",
password = "p12345";
if (username === "mbrsagor" && password === "p12345") {
console.log("your login successfully");
} else {
throw new Error(`Oops, you didn’t match`);
}
} catch (e) {
console.log(e.message);
} finally {
console.log(`Thanks for try login :)`);
}
console.log("\n");
// Example 3
new Promise((resolve, reject) => reject(false))
.catch((e) => {
let num = 20,
num2 = 330;
let reuslt = num / num2;
console.log(reuslt, e);
return 200;
})
.finally((a) => {
console.log(`Finally ${a}`);
return 300;
})
.then((response) => console.log(response));
// Example 4
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
fetch("http://httpstat.us/500")
.then(handleErrors)
.then((response) => console.log("ok"))
.catch((error) => console.log(error));
// Example 5
const url = "https://jsonplaceholder.typicode.com/posts/";
async function APIwithcatch() {
try {
var response = await fetch(url);
if (!response.ok) throw await response.json();
console.log(response.json());
} catch (e) {
console.log(e);
}
}
APIwithcatch();