Short Version: Is there a/what is the suggested way to return error details to the client when an exception is thrown in an AJAX-Enabled WCF Service (aside from just throwing the gates open and sending back all of the exception details)?
Long Version:
I’ve got a relatively simple AJAX-enabled WCF service that I’m calling from the client using the default service proxy. I’ve provided code snippets below, but I do not believe there is anything wrong with the code per se.
My problem is that if I throw an exception in the service, the error object returned to the client is always generic:
{
"ExceptionDetail":null,
"ExceptionType":null,
"Message":"The server was unable to process the request..."
"StackTrace":null
}
Ideally I would like to display different error messages on the client depending on what went wrong.
One option is to allow exceptions in WCF faults, which would provide me with the full stack trace and everything, but I appreciate the security concerns with this, and that’s actually a lot more information than I need. I could make do with just being able to send back a string describing the problem or something, but I don’t see a way to do this.
My Service Code:
[ServiceContract(Namespace = "MyNamespace")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService
{
[OperationContract]
public void DoStuff(string param1, string etc)
{
//Do some stuff that maybe causes an exception
}
}
On the client:
MyNamespace.MyService.DoStuff(
param1,
etc,
function() { alert("success"); },
HandleError);
where “HandleError” is just a generic error handling method that would display details about the error.
EDIT: Updated the post with a proper custom json error handler
The quick but non-preffered way.
In Your service behavior will give you all the details you need.
The Nice way
All exceptions from the application are converted to an
JsonErrorand serialized using aDataContractJsonSerializer. TheException.Messageis used directly. FaultExceptions provide the FaultCode and other exception are threated as unknown with faultcode -1.FaultException are sent with HTTP status code 400 and other exceptions are HTTP code 500 – internal server error. This not nescessary as the faultcode can be used to decide if it is and unknown error. It was however convenient in my app.
The error handler
Webbehaviour used to install the above error handler
The json error data contract
Specifies the json error format.
Add properties here to change the error format.
Using the error handler
Self-hosted
App.config