⊗jsSpExcJSE 149 of 294 menu

JavaScript-da JSON bilan bog'liq istisno misoli

Faraz qilaylik, tashqi dunyodan qandaydir joydan bizga mahsulot bilan bog'liq JSON keladi:

let json = '{"product": "apple", "price": 1000, "amount": 5}'; let product = JSON.parse(json); alert(product.price * product.amount);

Siz allaqachon bilasizki, JSON.parse metodi JSON noto'g'ri bo'lsa, istisno qo'yadi. Keling, ushbu istisnoni ushlaymiz:

try { let json = '{"product": "apple", "price": 1000, "amount": 5}'; let product = JSON.parse(json); alert(product.price * product.amount); } catch (error) { // istisnoga qandaydir tarzda javob beramiz }

Biroq, shunday bo'lishi mumkinki, JSON o'zi to'g'ri bo'lsin, lekin bizga kerakli maydonlarni o'z ichiga olmasin, masalan, narx maydoni yo'q:

let json = '{"product": "apple", "amount": 5}'; // narx yo'q

Keling, aytaylik, bu ham istisno vaziyat va shunday holatlarda o'zimizning foydalanuvchi istisnomizni qo'yamiz:

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: 'mahsulotda narx yoki miqdor yo\'q' }; } } catch (error) { // istisnoga qandaydir tarzda javob beramiz }

Endi catch bloki ikkita turdagi istisnolarni qabul qiladi: yoki JSON umuman noto'g'ri, va unda SyntaxError turidagi istisno bo'ladi, yoki JSON to'g'ri, lekin kerakli maydonlarni o'z ichiga olmaydi, va unda ProductCostError turidagi istisno bo'ladi.

Keling, catch blokida ushbu istisno turlarini ushlaymiz:

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: 'mahsulotda narx yoki miqdor yo\'q' }; } } catch (error) { if (error.name == 'SyntaxError') { alert('Noto\'g\'ri JSON mahsulot'); } else if (error.name == 'ProductCostError') { alert('Mahsulotda narx yoki miqdor yo\'q'); } }

Faraz qilaylik, sizga quyidagi ko'rinishdagi JSON keladi:

let json = `[ { "name": "user1", "age": 25, "salary": 1000 }, { "name": "user2", "age": 26, "salary": 2000 }, { "name": "user3", "age": 27, "salary": 3000 } ]`;

Ushbu JSONni tahlil qilishda umumiy to'g'riligini tekshiring, va tahlildan so'ng natijada massiv olinganligini, boshqa narsa emasligini tekshiring. Agar natijada massiv bo'lmasa - istisno qo'ying.

estrkkuzlpt