Aashish Kumar
Aashish Kumar

Reputation: 123

Exception handling in ASP.NET (C#) web services

I was looking for a way to transfer the exception message in web services of my asp.net application to the ajax error callback function. All I could find was catching an exception thrown from web service into a C# code but i am calling my service from ajax code and not a C# code. I want something more than the HTTP status codes returned.
Here is catch block of my Service code:

catch (Exception ex)
        {
            var fault = new GenericFault { Message = ex.Message, Operation = "" };
            throw new FaultException<GenericFault>(fault);
        }
    }

And here is my ajax error callback:

 error: function (err) {
         alert("The server encountered an error, please resubmit your request. If the problem persists, contact your administrator.");
         return 'error occured';
    }

I have already tried throwing web fault exception but that also didn't serve the purpose as only the HTTP status code gets passed.

Upvotes: 4

Views: 3538

Answers (1)

Aashish Kumar
Aashish Kumar

Reputation: 123

Found an answer. The trick lies in throwing right exception.
As the error caught in the callback error function sees the details in xhr object.
So you need to throw the HttpException passing with it status code and string message. catch block should look something like:

catch (Exception ex)
        {
             throw new HttpException(500, ex.Message);

          }

then your ajax callback will get the ex.message that you are passing from here:

error: function (err) {
     alert("The Detailed server error is "+err.responseJSON.Message);
     return 'error occured';
}

Upvotes: 3

Related Questions