2

Does anyone know of a situation in which the Database.convertLead() method fails by returning errors in the LeadConvertResult object that it returns, rather than throwing an exception? I'm trying to handle that situation like this:

Database.LeadConvertResult lcr = Database.convertLead(lc);
if (!lcr.IsSuccess()) {
    errormsg = lcr.errors.get(0).message;
    return null;
}

but all of the approaches I've tried in my test cases to force an error on convertLead result in an exception being thrown instead of returning an object where IsSuccess() returns false.

Maybe I shouldn't worry so much about being at 98% test coverage rather than 100%, but it's bugging me, and I'm wondering if the proper approach to handling these errors is try/catch rather than checking the result. Can anyone offer some suggestions? Thanks!

1

There's two versions of most Database methods. The first version accepts a single parameter, either a single value or a list, and the second version accepts an additional Boolean value called allOrNone. In the single-parameter version, allOrNone is assumed to be true, so normally you'd only call the two-parameter version if you wanted to set the value to false.

When allOrNone is set to true, any error causes a DMLException to be thrown. When allOrNone is set to false, however, you can then receive errors normally in the LeadConvertResult return value. Since you're using the single parameter version of convertLead, isSuccess will always be true if your code reaches that point in execution, because otherwise an exception would have been thrown.

When you pass a single value rather than a list, the allOrNone parameter serves to control how errors are indicated. True means a DMLException will always be thrown when an error occurs, while false means errors are returned normally in the getErrors call from the LeadConvertResult return value. However, even with allOrNone set to false, an exception can still bubble up to your code, for example, if you have a trigger which causes a NullPointerException.

In the code you've written, I would call the conditional statement an impossible condition; it will never, ever execute because the only legal value when allOrNone is true is that isSuccess will also be true.

  • Ah, so rather than try to force an error to get my coverage, I can just remove the code that can never be executed. That works for me! Thanks! – Jeff Garbers Mar 23 '16 at 18:36

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.