77

The problem is that the constructor for the AuraHandledException only sets the string argument to be the message sent to the client-end, while calling getMessage() on the exception through apex returns a different string that the constructor defaults to the value "Script-thrown Exception". Obviously, this leaves something to be desired for testing purposes, ...


66

Pros One of the primary advantages of the Pokemon Catch is that you reduce the complexity of code in many cases. For example, if you're concerned about a NullPointerException, a CalloutException, a QueryException, and a DmlException, you have two choices: try { ... } catch(NullPointerException npe) { ... } catch(CalloutException ce) { ... } catch(...


48

As far as I know, @BigAssForce was the first to discover this change in this answer to a question by @DanielBallinger. Despite the documentation's claims to the contrary, the compiler now allows built-in Exception types to be constructed. I confirmed through Execute Anonymous with the following snippet: try { CalloutException e = new CalloutException();...


26

The record is locked because you are catching the record after the insert DML statement has happened. So if you'd like to modify this record (or records), you will need to query anew, modify, then execute another DML statement. Here is an example of how you could modify your trigger to work: trigger SetProductCategory on OpportunityLineItem (after insert) {...


26

In Java, I'd agree with the sfdcfox's takeaway. But (particularly in the absence of documentation about which Exceptions Apex will throw), catching Exception can make a lot of sense. I tend to go through various stages as the code goes through its lifecycle and end up with a hybrid where I catch some things specifically, then catch 'em all in the end. For ...


23

Update, Summer '17: Platform Events are now GA. Note the following from the docs: Platform Events and Transactions Unlike custom objects, platform events aren’t processed within database transactions in the Force.com platform. As a result, publishing platform events can’t be rolled back. Note the following: The allOrNoneHeader API header is ...


21

From Winter16 you can check this using the Approval system class Pass it the Id of a record you want to check if is locked or not: Approval.isLocked(recordId); Make sure you set the class api version to 35.0 or higher!


20

Three problems here: (a) Date receiving DateTime value. The value should be "YYYY-MM-DD" only. (b) Decimal receiving String value. The value should not be in quotes. (c) You must not have a trailing comma. JSON-compliant strings are more strict than normal JavaScript. [{ "name":"OpportunityABC", "CloseDate":"2017-06-03", "StageName":"Pre-...


19

Per the Governor Limits, you can only send 5000 single emails a day (or less, depending on license). Using the API or Apex, you can send single emails to a maximum of 5,000 external email addresses per day based on Greenwich Mean Time (GMT). Single emails sent using the Salesforce application don't count toward this limit. There’s no limit on ...


18

I realize I'm a "late comer" to answering this question, but it was closed by the time I saw it initially. Now that it's been reopened, I feel I have something important to add that's not been given consideration so want to add my thoughts. Exceptions are about validating Data Exactly what are exceptions? Exceptions are, for the most part, about validating ...


15

I wrote a bit on my blog last week about how I was using the Tooling api to effectively create an "eval()" method. You could replace the transaction mechanism with a similar eval mechanism. The "eval'd" transaction code would still roll everything back, but the get message would be available for the eval exception to return. see http://codefriar.wordpress....


14

Please check this link it may help: https://help.salesforce.com/apex/HTViewSolution?id=000003701 You have uncommitted work pending. Please commit or rollback before calling out" Description Sometimes a developer needs to create a record and then update it with information provided by a Web Service. However, a Web Service Callout may not occur after ...


14

Here are my views on this: Is it ever acceptable (or even preferable) to catch a generic Exception in Apex? Yes, there are definitely situations where a generic Exception is acceptable or preferred. Prerequisite conditions: You don't want to show ugly error messages to the end user. You have logging provisions in your system. Situation You are working ...


12

Aside from that last sentence the documentation is spot on. However, I would argue that the behavior is correct, and it is just that sentence which is flawed. It is easy to demonstrate that for a custom object, it is flat out incorrect. What they mean is an instance of a custom defined class. Let's check: Script class Demo { } Demo instance = (Demo)JSON....


11

It looks like System.ProcedureException is yet another uncatchable exception. I think your only option here is to avoid having that exception thrown. You can detect if you're in an unmanaged context with some careful use of the UserInfo. isCurrentUserLicensed method. A careful read of the docs shows it throws a System.TypeException if the namespace passed ...


11

You can't catch LimitException. They are a special class of fatal error that simply cause your code to blow up the minute you hit one. So your only strategy is going to be avoidance. Counting invocations of this code is one way, but that will only work if this is the only place batch jobs can be scheduled. Keeping a system-wide counter (e.g. batch jobs ...


11

Here is my attempt to combine all of the answers given, and to interpret the SF Documentation provided on email limits. A SINGLE_EMAIL_LIMIT_EXCEEDED exception is thrown when the daily Messaging.SingleEmailMessage limit is exceeded. This exception can be thrown in other cases as well, like when email deliverability is not set correctly. Each ...


11

System.UnexpectedException gets thrown a lot with Note inserts if you do not prepare the content exactly right, and they cannot be caught or handled in any way. I wrote an open source package a while ago to abstract over some of these issues. From its documentation, a summary of the requirements: The following steps are required to prepare note content for ...


10

Force.com Platform Apex Versioning and Feature/Field Visibility The platform (or more specifically Apex runtime) often (but not always) conditions the visibility of various features (including fields on objects) based on the API version (linked with platform version) associated with Apex code file containing the code being run. This way new features ...


10

While you can't catch a LimitException (which seems strange since it let's you define a catch block for it), you can query how many batch jobs are running and use that to determine if you have the resources available to submit a batch job. Unfortunately there isn't a limits method for batches so you'll have to hard code it for now. Example Integer ...


10

You should really know a more specific type of Exception. If you are working out how to get the try block to throw an exception at all, see the bottom section. If you know calling a method will cause an Exception and want to make sure it is handled by that method, your assert(false) should be in the catch block, not try. A common pattern is: try { ...


9

siteName = con[0].Site__r.Name; con[] has no elements so trying to access the 0 index element will cause the list index out of bounds excpetion. To protect against this you could change your code to first check to see if the returned List is not empty: if (!con.isEmpty()) { siteName = con[0].Site__r.Name; } You may want to add in an else condition to ...


9

First please take a look at this answer for a partial solution / approach, Can I prevent an insert to be rolled back even if my class (later) runs into an exception?. Basically as per the Apex Developers guide the final commit transaction management is baked into Apex, meaning it will always rollback if you let the platform handle your exceptions, if you ...


9

Exception Cause The key issue that is causing that exception is that you are trying to assign a Group Id to a User Lookup. You need to make sure it is a User Id first. if (obj.OwnerId.getSObjectType() == User.sObjectType) obj.SomeField__c = obj.OwnerId; Why It Wasn't Caught The line where you assign the OwnerId does not cause an Exception. It causes the ...


9

Custom Metadata supports a limited SOQL syntax, and "OR" statements are not supported. From the documentation: Custom metadata types support the following SOQL query syntax. SELECT fieldList [...] FROM objectType [USING SCOPE filterScope] [WHERE conditionExpression] [ORDER BY field {ASC|DESC} [NULLS {FIRST|LAST}] ] The fieldList can include ...


9

There are two ways to handle exceptions in Apex Code: reactive or preemptive. In reactive model of exception handling, we react to an exception, by using try-catch. In the preemptive model of exception handling, we anticipate exceptions and avoid creating situations where the exception can occur. For example, here's the same code written in reactive ...


9

You can actually work around the problem of custom exceptions failing to provide stacktraces... Here's an abstract class that you can extend instead of Exception itself: public abstract class StackTraceException extends Exception { private String stackTrackString = createStackTraceString(); private String createStackTraceString() { ...


9

Found this interesting statement in the idea Need a reliable developer script exception alert mechanism: Salesforce R&D has acknowledged the issue but states it is a feature frozen area therefore, there is no known issue is being worked on. R&D is planning to replace this feature with full-featured exception handling/notification/management system. ...


8

You can send a test message with no parameters, and check the resulting error code. BCC Compliance is checked before other validations, so this should be reliable. Boolean bccComplianceEnabled; Messaging.SingleEmailMessage m = new messaging.singleEmailmessage(); m.bccsender = true; try { Messaging.sendEmail(new messaging.singleemailmessage[] { m }); } catch(...


8

As per the documentation of Outbound Email: The email is not sent until the Apex transaction is committed. An unhandled exception will cause the Apex transaction to roll back, cancelling the e-mail. A solution for you would be to mark the notifyDevelopersOf() function with @future. This will create a new request and transaction for the execution function....


Only top voted, non community-wiki answers of a minimum length are eligible