Try - Catch / JSON | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Try - Catch / JSON

Hello, I need to wrap the function that get JSON and make JS-object from it. Function is ready - function convertCurrency(amount, from, to) { let x = JSON.parse(loadCurrencyJSON()); return +((x[from] / x[to]) * amount).toFixed(2); } But if JSON is not valid I have error. How to wrap the function in "try-catch" the right way? Привет, земляки) Есть функция, которую надо обернуть в try-catch для случаев, когда получаемый JSON невалидный. Что-то сегодня дико туплю с похмелья)) В очередной раз убеждаюсь, что синька и кодинг плохо совместимые вещи) Функция выше. Заранее спасибо!

19th Apr 2018, 7:50 AM
xphnx
xphnx - avatar
3 Answers
+ 9
you can wrap the entire function content in try catch function convertCurrency(amount, from, to) { try{ let x = JSON.parse(loadCurrencyJSON()); return +((x[from] / x[to]) * amount).toFixed(2); }catch(e){ return "error occured: " + e; } }
19th Apr 2018, 8:23 AM
Burey
Burey - avatar
+ 8
no probs :)
19th Apr 2018, 8:28 AM
Burey
Burey - avatar
+ 4
thanx, Burey!
19th Apr 2018, 8:24 AM
xphnx
xphnx - avatar