Error Handling With Webhttpbinding For Ajax Json
Contents |
shipped with .net Framework 3.5. This binding along with WebHttpBehavior will be your friend for REST, POX & AJAX scenarios. When you expose an endpoint using WebHttpBinding the default error handling webfaultexception wcf rest mechanism is overridden by a custom error handler added by
Wcf Return Json Exception
the WebHttpBehavior. Now if you throw a FaultException from your methods – this handler will simply outgoingwebresponsecontext swallow your exception and will generate a generic 400 Bad Request error message. It will do the same for non-fault exceptions. The reason for this change is
Wcf Webfaultexception
that in the SOAP world, Faults have a well known wire representation and based on that your FaultException is translated into a SOAP fault message. There is no such wire representation for the faults in REST or AJAX scenarios. If you own both sides (client & service) of the solution, you might want to ierrorhandler customize this default WCF behavior. For example, in my scenario I want to send fault object as a JSON string to the client with a 400, “Bad request” http error code. For non-fault exception I will return a generic message with 500 “Internal Server Error”. First step of this customization is to subclass the WebHttpBehavior and replace the default error handler with you own error handler. public class WebHttpBehaviorEx : WebHttpBehavior { protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { // clear default erro handlers. endpointDispatcher.ChannelDispatcher.ErrorHandlers.Clear(); // add our own error handler. endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new ErrorHandlerEx()); } } Create your own error handler by impelemting IErrorHandler interface. public class ErrorHandlerEx : IErrorHandler { public bool HandleError(Exception error) { return true; } public void ProvideFault( Exception error, MessageVersion version, ref Message fault) { //TODO: here we can provide our own fault } } ProvideFault implemen
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it http://zamd.net/ajax/2008/07/08/error-handling-with-webhttpbinding-for-ajaxjson.html only takes a minute: Sign up Error Handling in WCF WebHttp Services with WebFaultException only xml formated exception up vote 2 down vote favorite 2 Im trying to get WebFaultException to be returns as json and xml depending on what the client asks for as described in http://blogs.msdn.com/b/endpoint/archive/2010/01/21/error-handling-in-wcf-webhttp-services-with-webfaultexception.aspx My service interface looks like this [OperationContract] [WebInvoke(Method = "POST", UriTemplate = http://stackoverflow.com/questions/8167202/error-handling-in-wcf-webhttp-services-with-webfaultexception-only-xml-formated "session_record?id={id}&command={command}")] void SessionRecord(Guid id, String command); The exception throw new WebFaultException
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of http://stackoverflow.com/questions/6563736/cant-get-info-from-faultexceptions-javascript this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask http://www.robbagby.com/rest/effective-error-handling-with-wcf-rest/ Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign error handling up Cant get info from FaultExceptions (javascript) up vote 2 down vote favorite Until now I have used an webservice ASMX which I call from javascript. It has been working fine, but because I needed some control over the serialization, I am trying to switch to DataContracts and WCF. However, I do believe that there is something I have misunderstood, because Im trying error handling with to catch faultexceptions from the client code (javascript), but the only errorcode Im receiving is: (translated, so might not be accurate) "The server could not handle the request because of an intern error. You can get more info about the error by activate IncludeExceptionDetailInFaults..." I have tried to set IncludeExceptionDetailInFauls to true which gives some info, but as far as I understood, the whole point by throwing FaultExceptions is to hide exceptions from the user, and only throw a little info? Im trying with a IErrorHandler, but I have created a simpler example: The SVC: [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class WcfTest { // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json) // To create an operation that returns XML, // add [WebGet(ResponseFormat=WebMessageFormat.Xml)], // and include the following line in the operation body: // WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; [OperationContract] public string DoOk() { // Add your operation implementation here return "Success"; } [OperationContract] public string DoFail() { FaultReason reason = new FaultReason("Fail <- This is good :)"); throw new FaultException(reason); return "Success"; } } which is included with a scriptmanager, and
services. In this post, I will illustrate how to expose, as well as handle errors effectively when working with RESTful WFC services. Watch the Screencast Watch the screencast on Channel9. The Sample Service As you can see from the ServiceHost directive, we are using the configurationless model. By setting the factory to WebServiceHostFactory, we do not need to define all of the configuration settings in the web.config under System.serviceModel. The WebServiceHostFactory will dynamically set up an instance of the WebServiceHost in response to requests. The WebServiceHost will set up a default endpoint, if appropriate, with the binding set to webHttpBinding (read REST-Friendly binding). Further, this host will add the WebHttpBehavior to the endpoints. The WebServiceHostFactory is our RESTful factory and first shipped with WCF 3.5 (with Visual Studio 2008 sp1). Examining the service implementation, it is clear that this is a relatively simple service operation that we are exposing. The operation returns a page of wines from our wine catalog (by page, I am referring to returning a subset of wines (1 to x out of y) instead of the complete set). We decorated the operation with a WebGet, exposing the service over an HTTP GET. We further set the ResponseFormat to JSON and set up a friendly UriTemplate. If the above concepts are foreign to you, or you want a refresher on the basics of REST in WCF, check out all of my blog posts on the subject. The last thing to notice is that if someone passes an invalid pageSize, we are throwing an ApplicationException. This is what you might expect to see in a typical .NET implementation. The next step is to cover the basics of errors in RESTful services. REST and Errors As you probably know, the underlying theme of REST is to embrace the key protocols of the web. The means in which a successful or failed call is conveyed to the requestor in HTTP is via an HTTP status code. We are all familiar with at least a few of these: 200: OK, 404: Not Found: 400: Bad Request and 500: Internal Server Error. What you may not know is that the codes are logically grouped as follows: 100-199 – Informational 200-299 - Client request successful 300-399 - Client request redirected, further action necessary 400-499 - Client request incomplete 500-599 - Server error The appropriate status code is returne