Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 436917
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T20:31:34+00:00 2026-05-12T20:31:34+00:00

Short Version: Is there a/what is the suggested way to return error details to

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T20:31:34+00:00Added an answer on May 12, 2026 at 8:31 pm

    EDIT: Updated the post with a proper custom json error handler

    The quick but non-preffered way.

    <serviceDebug includeExceptionDetailInFaults="true"/>
    

    In Your service behavior will give you all the details you need.

    The Nice way

    All exceptions from the application are converted to an JsonError and serialized using a DataContractJsonSerializer. The Exception.Message is 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

    internal class CustomErrorHandler : IErrorHandler
    {
        public bool HandleError(Exception error)
        {
            //Tell the system that we handle all errors here.
            return true;
        }
    
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            if (error is FaultException<int>)
            {
                FaultException<int> fe = (FaultException<int>)error;
    
                //Detail for the returned value
                int faultCode = fe.Detail;
                string cause = fe.Message;
    
                //The json serializable object
                JsonError msErrObject = new JsonError { Message = cause, FaultCode = faultCode };
    
                //The fault to be returned
                fault = Message.CreateMessage(version, "", msErrObject, new DataContractJsonSerializer(msErrObject.GetType()));
    
                // tell WCF to use JSON encoding rather than default XML
                WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
    
                // Add the formatter to the fault
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
    
                //Modify response
                HttpResponseMessageProperty rmp = new HttpResponseMessageProperty();
    
                // return custom error code, 400.
                rmp.StatusCode = System.Net.HttpStatusCode.BadRequest;
                rmp.StatusDescription = "Bad request";
    
                //Mark the jsonerror and json content
                rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
                rmp.Headers["jsonerror"] = "true";
    
                //Add to fault
                fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
            }
            else
            {
                //Arbitraty error
                JsonError msErrObject = new JsonError { Message = error.Message, FaultCode = -1};
    
                // create a fault message containing our FaultContract object
                fault = Message.CreateMessage(version, "", msErrObject, new DataContractJsonSerializer(msErrObject.GetType()));
    
                // tell WCF to use JSON encoding rather than default XML
                var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
    
                //Modify response
                var rmp = new HttpResponseMessageProperty();
    
                rmp.Headers[HttpResponseHeader.ContentType] = "application/json";
                rmp.Headers["jsonerror"] = "true";
    
                //Internal server error with exception mesasage as status.
                rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
                rmp.StatusDescription = error.Message;
    
                fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
            }
        }
    
        #endregion
    }
    

    Webbehaviour used to install the above error handler

    internal class AddErrorHandlerBehavior : WebHttpBehavior
    {
        protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            base.AddServerErrorHandlers(endpoint, endpointDispatcher);
    
            //Remove all other error handlers
            endpointDispatcher.ChannelDispatcher.ErrorHandlers.Clear();
            //Add our own
            endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new CustomErrorHandler());
        }
    }
    

    The json error data contract

    Specifies the json error format.
    Add properties here to change the error format.

    [DataContractFormat]
    public class JsonError
    {
        [DataMember]
        public string Message { get; set; }
    
        [DataMember]
        public int FaultCode { get; set; }
    }
    

    Using the error handler

    Self-hosted

    ServiceHost wsHost = new ServiceHost(new Webservice1(), new Uri("http://localhost/json")); 
    
    ServiceEndpoint wsEndpoint = wsHost.AddServiceEndpoint(typeof(IWebservice1), new WebHttpBinding(), string.Empty);
    
    wsEndpoint.Behaviors.Add(new AddErrorHandlerBehavior());
    

    App.config

    <extensions>  
      <behaviorExtensions>  
        <add name="errorHandler"  
            type="WcfServiceLibrary1.ErrorHandlerElement, WcfServiceLibrary1" />  
      </behaviorExtensions>  
    </extensions> 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Short and sweet version: Is there a single web service method that would return
The short version: is there a way to to write an and or an
Short version: I want a way to run somefunction(username) and have it return the
Short version: Is there a simple, built-in way to identify the calling view in
Short version: Is there a simple way to get the value of a primary
Short Version Is there a way to force (or provide a hint to) Microsoft
Short version: When two lists are adjacent to each other, is there a way
Is there a cleaner way to get the short version hash of HEAD from
short version: Is there a good time based sampling profiler for Linux? long version:
Short version question : Is there navigator.mozIsLocallyAvailable equivalent function that works on all browsers,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.