JavaScript-də JSON istisnası nümunəsi
Tutaq ki, xarici dünyadan bizə məhsulla bağlı JSON gəlir:
let json = '{"product": "apple", "price": 1000, "amount": 5}';
let product = JSON.parse(json);
alert(product.price * product.amount);
Artıq bilirsiniz ki, JSON.parse metodu
JSON düzgün olmadıqda istisna atacaq.
Gəlin bu istisnanı tutaq:
try {
let json = '{"product": "apple", "price": 1000, "amount": 5}';
let product = JSON.parse(json);
alert(product.price * product.amount);
} catch (error) {
// istisnaya nə isə şəkildə reaksiya veririk
}
Lakin, ola bilər ki, JSON özü düzgün olsun, amma bizə lazım olan sahələri ehtiva etməsin, məsələn, qiymət sahəsi yoxdur:
let json = '{"product": "apple", "amount": 5}'; // qiymət yoxdur
Gəlin deyək ki, bu da istisnai vəziyyətdir və belə halda öz istifadəçi istisnamızı atacağıq:
try {
let json = '{"product": "apple", "amount": 5}';
let product = JSON.parse(json);
if (product.price !== undefined && product.amount !== undefined) {
alert(product.price * product.amount);
} else {
throw {
name: 'ProductCostError',
message: 'məhsulda qiymət və ya miqdar yoxdur'
};
}
} catch (error) {
// istisnaya nə isə şəkildə reaksiya veririk
}
İndi catch bloku iki növ
istisna alacaq: ya JSON ümumiyyətlə düzgün deyil,
və onda SyntaxError tipli istisna olacaq,
ya da JSON düzgündür, amma lazımi
sahələri ehtiva etmir, və onda ProductCostError tipli
istisna olacaq.
Gəlin catch blokunda bu
istisna növlərini tutaq:
try {
let json = '{"product": "apple", "amount": 5}';
let product = JSON.parse(json);
if (product.price !== undefined && product.amount !== undefined) {
alert(product.price * product.amount);
} else {
throw {
name: 'ProductCostError',
message: 'məhsulda qiymət və ya miqdar yoxdur'
};
}
} catch (error) {
if (error.name == 'SyntaxError') {
alert('Yalnış JSON məhsulu');
} else if (error.name == 'ProductCostError') {
alert('Məhsulda qiymət və ya miqdar yoxdur');
}
}
Tutaq ki, sizə bu cür JSON gəlir:
let json = `[
{
"name": "user1",
"age": 25,
"salary": 1000
},
{
"name": "user2",
"age": 26,
"salary": 2000
},
{
"name": "user3",
"age": 27,
"salary": 3000
}
]`;
Bu JSON-u ümumi düzgünlüyə görə parçalama zamanı yoxlayın, və parçalamadan sonra yoxlayın ki, nəticədə massiv alınır, ya nə isə başqa. Əgər nəticədə massiv alınmır - istisna atın.