Mocking a webservice CalloutException for a SOAP Fault

It's possible to scaffold a System.CalloutException by deserializing it into existence or instantiating it with the type. Then you can throw it in your mock:

Adrian Larson notes that as of API v36.0 you can just construct them :-)

@TestVisible class ResponseMock implements WebServiceMock {
    public void doInvoke(
        Object stub,
        Object request,
        Map<String, Object> response,
        String endpoint,
        String soapAction,
        String requestName,
        String responseNs,
        String responseName,
        String responseType
    ) {
        CalloutException e = new CalloutException();
        e.setMessage('Validation Error(s) occurred during Foo Get.');
        throw e;
    }
}

Inject it into your test with the normal HTTP mock method:

Test.setMock(WebServiceMock.class, new ResponseMock());
client.doTheCallout();

Just extending the findings of @BigAssForce. Not trying to steal any thunder, but this is too long to be a comment.

In Creating Custom Exceptions, the documentation still claims:

Since you can’t throw built-in Apex exceptions but can only catch them, you can create custom exceptions to throw in your methods.

Despite this assertion, 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();
    e.setMessage('This is a constructed exception!');
    throw e;
}
catch (Exception pokemon)
{
    system.debug(pokemon);
}

I went through the whole list and what do you know? The following types can all be constructed and thrown:

  • AsyncException
  • CalloutException
  • DmlException
  • EmailException
  • ExternalObjectException
  • InvalidParameterValueException
  • LimitException (though it still can't be caught)
  • JSONException
  • ListException
  • MathException
  • NoAccessException
  • NoDataFoundException
  • NoSuchElementException
  • NullPointerException
  • QueryException
  • RequiredFeatureMissingException
  • SearchException
  • SecurityException
  • SerializationException
  • SObjectException
  • StringException
  • TypeException
  • VisualforceException
  • XmlException