简体   繁体   中英

How do I fix it 'error: undefined' in javascript?

When I type '5' and 'asd' in this code, I want it showing 'Error: Not a number.', but it shows 'Error: undefined'. So, what's the problem? I can't find where it is wrong.

 function productOf(num1, num2) { try { if (isNaN(num1) || isNaN(num2)) { alert('This is not a number, please try it again.'); throw new Error('Not a number.'); } else { return num1 * num2; } } catch (err) { console.error(err.name + ': ' + err.messsage); } } inputNum1 = window.prompt('Please enter a number: '); inputNum2 = window.prompt('Please enter your second number: '); console.log(productOf(inputNum1, inputNum2)); 

The problem is simply that your catch is logging out err.messsage instead of err.message . This results in the custom error not being able to be thrown at all.

Simply correcting this as err.message instead of err.messsage resolves the problem, as is seen in the following:

 function productOf(num1, num2) { try { if (isNaN(num1) || isNaN(num2)) { alert('This is not a number, please try it again.'); throw new Error('Not a number.'); } else { return num1 * num2; } } catch (err) { console.error(err.name + ': ' + err.message); } } inputNum1 = window.prompt('Please enter a number: '); inputNum2 = window.prompt('Please enter your second number: '); console.log(productOf(inputNum1, inputNum2)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM