57

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


51

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


33

You can use this(message) in your constructor to call the base class constructor: public virtual class MyException extends Exception { public Decimal d; public MyException(String message, Decimal d) { this(message); this.d = d; } @isTest static void test() { try { throw new ...


27

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


23

Update 26th Oct: See below for a second version following comments below I have just promoted this idea as well, I would never have imagined it to be a good design for this method to have it throw an unhandled exception, IMHO that is! Anyway, since we are being inventive here, the following also seems to do the trick. But be aware much like the custom ...


23

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


22

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


19

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!


17

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


16

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


16

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 think that the issue here is that an aggregate query is considered to have accessed every record included in the aggregation. Thus the 50000 row limit isn't the number of records returned by the query, its the number of records 'touched'. As you have a clause of 'LIMIT 50000', you are asking for a maximum of 50000 aggregates to be returned by the query ...


14

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


13

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


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

We did notice this as well, however we tend to now use Subscriber support to login and reproduce the issue. If you login via Subscriber support you can see the stack traces and full debug information for you packages. Take a look at the answer to this question for more information about the Subscriber Support feature, it's a must for an ISV!


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


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

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

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


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


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


8

I cannot seem to reproduce what you've described, I get the sObject not retrieved error for Case 1 too! The only caveat would be that since sObjects are passed by reference, hopefully there isn't a sneaky bit of assignment which is setting the value of CustomField1 somewhere in the foodchain. If there is an assignment of value then it wouldn't throw the ...


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


8

As a follow up to this thread and to answer this question should anyone happen up this, here is what I discovered: The Auth.RegistrationHandler interface at the heart of this question has two main methods, as Andy noted, createUser() and updateUser(). The former returns a user and the latter is a void method. I tried Andy's suggestion and pattern of try/...


8

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


8

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


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