Apex classes have concept of Exception handling. This is similar to all other languages.
You can create an custom Exception class by extending the standard Exception
class of the Apex.
You should go through following documentation: An Introduction to Exception Handling
By implementing your own Exception class class whenever you want to interrupt the code simply throw exception as:
throw new MyCustomException(' The Error Message');
Simple Example:
try
{
// Own exception class extending the standard Exception class.
throw new MyException('something bad happened!');
}
catch (MyException e)
{
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'my error msg');
futureCreateErrorLog.createErrorRecord(e.getMessage());
}
If you want to let the error come directly to user interface, do not cover statements with try-catch
(this is not recommended).
Trigger.new
, then anyaddError()
upon an sobject withinTrigger.new
will prevent the record from saving and generate an error message for the user. There is nothing aboutaddError()
that says it can only be coded in a trigger fileexecute(..)
does DML and that invokes a trigger that via its handler doesaddError(...)
, a DML exception is thrown and batchexecute()
can catch it. I would agree thataddError()
applied directly to the sobject in execute'sscope
argument wouldn't make much sense.