0

Is there any way that we can use addError() inside an apex class? I know it will work properly inside a trigger. But i would like to have a separate class for all validations instead writing them inside a trigger.

In the apex code it comes to the line and executes it but neither message will be displayed nor stop saving the record

Thanks, Lahiru

  • No message and saving. What do you expecting from adderror then? – Ilya Lepesh Apr 28 '16 at 5:46
  • If the validation class is passed Trigger.new, then any addError() upon an sobject within Trigger.new will prevent the record from saving and generate an error message for the user. There is nothing about addError() that says it can only be coded in a trigger file – cropredy Apr 28 '16 at 15:59
  • @cropredy Have you ever tried it from a batch? There are definitely contexts in which it cannot be used. – Adrian Larson Aug 31 '16 at 12:40
  • @AdrianLarson -- why wouldn't it work in batch? If execute(..) does DML and that invokes a trigger that via its handler does addError(...), a DML exception is thrown and batch execute() can catch it. I would agree that addError() applied directly to the sobject in execute's scope argument wouldn't make much sense. – cropredy Aug 31 '16 at 15:07
2

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).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.