-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry-catch.js
More file actions
25 lines (22 loc) · 739 Bytes
/
try-catch.js
File metadata and controls
25 lines (22 loc) · 739 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
function insert(arr, product) {
try {
if (!product || typeof product != 'object') {
throw new Error('Invalid Product')
}
if (arr.some(p => p.id === product.id)) {
throw new Error('Product already exists')
}
arr.push(product)
console.log(`Product inserted: ${JSON.stringify(product)}`)
} catch (error) {
console.error(`${new Date().toLocaleString()}. Error inserting product: ${error.message}`)
throw error //re-throw
}
}
const products = []
try {
insert(products, {id: 1, title: 'Laptop', price: 1000})
insert(products, {id: 1, title: 'Smartphone', price: 500})
} catch (error) {
console.log(`Error. ${error.message}`)
}