Error Handling
JavaScript supports try and catch blocks to handle errors. When something goes wrong, JavaScript will throw an error.
Syntax
try {
// The code to run
}
catch(err) {
// Code to handle any errors
}
Example
try {
var receiptDate = NSOA.form.getValue('date');
var travelDate = NSOA.form.getValue('TravelDate__c');
if ( receiptDate < travelDate ) {
NSOA.form.error('TravelDate__c', 'The travel date cannot be after the receipt date!');
}
}
catch(err) {
NSOA.meta.log('error', err.message);
}
See also:
Key points:
-
Use a try block to surround code that could throw an error.
-
Use a catch block to contain code that handles any errors.
-
You can use the throw statement to create custom errors.
throw
When an exception occurs JavaScript will throw an error that you can catch.
You can use the throw statement to raise your own custom exceptions. These exceptions can be captured and appropriate action taken.
// Function that throws a custom "Divide by zero" error
function divide(x,y) {
if( y == 0 ) {
throw( "Divide by zero" );
} else {
return x / y;
}
}
//Function that catches the custom error as a string
function test() {
try {
return divide(10,0);
}
catch(err) {
// err == "Divide by zero"
}
}
Note:
You can throw different types, e.g. String, Number, and Object.