Appendix C
JavaScript® Code for Error Handling
Read the directions carefully and write JavaScript® code that addresses the requirements.
Copy your code directly into this appendix document and post your assignment.
1. Write JavaScript® code that anticipates and handles an error for an expected numeric field. This code is executed on keypress, and the entered value is saved for you in a variable called enteredChar. Include the try block of JavaScript® statements needed to check if the character is not a number or a nonalphanumeric character, or if you throw an error message.
2. Write a custom error handling JavaScript® function called processErrors that handles a custom error by assigning it to the onerror event handler. Include the block of JavaScript® statements needed to pass the arguments sent by the JavaScript® interpreter into the processErrors function, send an alert message with the arguments, return, and write the event handler that calls the processErrors function.
1. function numCheck() { var enteredChar = document.getElementById('numeric_field').value;
var pattern = new RegExp('/^\d+$/'); // numbers only match
if (pattern.test(enteredChar)) { alert("All good!"); } else { try { throw new Error("Invalid numerical character(s) given!"); } catch (e) { alert(e); } }
}
The html is as follows:
<form>
Enter Numeric Value: <input type="text" id="numeric_field" onkeypress="numCheck()">
</form>
2 function processErrors(errMessage, errURL, errLineNum) { window.alert("The file " + errURL + " generated the following error: " + errMessage + " on line " + errLineNum + ", and the caller is "+arguments.caller.toString()); return true;
}
window.onerror=processErrors;