Force.com Custom Web Services - How to create a SOAP fault
Question:
The standard salesforce.com web services defines fault and exception code when there is an error calling the services. Can I define my own fault code and exception code when writing my custom web services? If so, can you provide some samples? Thanks a lot.
Answer:
Using Apex, you cannot explicitly create your own SOAP faults. However, SOAP faults are automatically created when an Exception is thrown. So, to create your own SOAP fault, you simply throw an Exception.
Of course, Apex doesn't allow you to throw a standard exception, so you need to create your own custom exception class to throw an exception. This isn't very hard to do. Here is very simple code to create your own exception class:
public class SOAPException extends Exception {}
That is it.
To throw the exception, you simply write:
throw new SOAPException();
Salesforce.com provides plenty of documentation on how to create the classes and throw the exceptions. The biggest thing to remember is that the custom exception class must actually have the name Exception in it. Why, I don't know, but that is the way it is.
Here is a good starting point to the documentation on custom exception classes.
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_exception.htm
The standard salesforce.com web services defines fault and exception code when there is an error calling the services. Can I define my own fault code and exception code when writing my custom web services? If so, can you provide some samples? Thanks a lot.
Answer:
Using Apex, you cannot explicitly create your own SOAP faults. However, SOAP faults are automatically created when an Exception is thrown. So, to create your own SOAP fault, you simply throw an Exception.
Of course, Apex doesn't allow you to throw a standard exception, so you need to create your own custom exception class to throw an exception. This isn't very hard to do. Here is very simple code to create your own exception class:
public class SOAPException extends Exception {}
That is it.
To throw the exception, you simply write:
throw new SOAPException();
Salesforce.com provides plenty of documentation on how to create the classes and throw the exceptions. The biggest thing to remember is that the custom exception class must actually have the name Exception in it. Why, I don't know, but that is the way it is.
Here is a good starting point to the documentation on custom exception classes.
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_exception.htm