Exception handler in a WCF REST service - wcf

I would like to create an exception handler in a WCF REST service. For Client recesse this exception in a simple way. I found many implementations using SOAP IErrorHandler for WCF, but none for REST. Could anyone help me with this?

Did you try using WebFaultException?

the exception information is provided in response message. Usually (in HTTP GET for REST), a result is expected as XML/JSON. In case of any error the error message is places instead of REST URI result.
http://www.robbagby.com/rest/effective-error-handling-with-wcf-rest/
WCF Rest Error Handling

IErrorHandler also works for WCF REST services, although you may need to know about how a non-SOAP (e.g., JSON) message is mapped inside the WCF Message object. The example at http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/07/wcf-extensibility-ierrorhandler.aspx shows an error handler used to format responses to a JS client (in JSON).

Related

Handing unauthorized requests in WCF?

We have an WCF service, using webhttp binding. Users get authenticated, and then a method is called. In the method, we check a variety of settings associated with the user and some information specific to the request before knowing if the user is authorized to make the call.
Since this is WCF, I think I should be throwing a FaultException of some sort, but it's not clear if there is best practices.
My thoughts are that once I know what exception I will be throwing, I'd add a IErrorHandler which would set the headers correctly to 403.
Two questions:
1) Is there a standard FaultException for unauthorized requests? i.e. the equivalent of the http status code of 403?
2) Should I be able to handle the exceptions that I'll be throwing and change the response code to 403? Will I be able to pass through a custom error message? I've seen some posts that setting headers using the operation context in a catch does not get propagated to the client.
Ideally I'd be able to set the status to 403 with additional information like "You must be part of the administrators group to add a user"
Because you're using webhttp binding, traditional WCF fault management is not pertinent here and it's better to use WebFaultException and WebFaultException<>.
Public string MyOperation()
// Operation logic
// ...
throw new WebFaultException<string>("You must be part of the administrators group to add a user", HttpStatusCode.Forbidden);
}
As you think, it's very important to use standard HTTP status codes when developping an HTTP (REST-like) service.
It's been my experience that throwing fault exceptions, at least with wshttpbinding and basichttpbinding, can cause your web service to fail, so I don't recommend that approach.
If you want to send a message back to unauthorized users, just send an HTML response, setting the status to any one of the 400 responses that seem appropriate.
But from experience, fault exceptions, even if they're a controlled response to user actions and not from an actual processing error, will cause your web service to fail. I think they should be reserved genuine processing exceptions.
I went ahead and derived custom exceptions from FaultException, and then added an IErrorHandler to set the appropriate headers.
This seemed to be the best of both worlds. The code only throws exceptions derived from ones used in WCF, and all the handling specific to http binding is done via an IErrorHandler outside the business logic.

Include exception information in return values in WCF

I am implementing an IErrorHandler for a set of WCF services. I configure the WCF services to use this error handler via the configuration file, using a custom behavior.
All methods in all services return a value that is derived from a common base class.
What I want to do is to include information about the error in the return value if the error handler gets called.
Any ideas on how to do this elegantly would be much appreciated.
You just need to create the message manually which complies with your return SOAP data. You can implement your own body writer and use it for the Message.Create function. Here is a good example of how to accomplish what you basically need Simple custom error handler for webHttpBinding in WCF
However if I were you I would choose fault approach when you just return void or some data if everything succeeds and fault message if it fails. Of course if there are no strict requirements to return operation status in the response object or if you are not refactoring an existing system.
Hope it helps.

Is returning an object or an exception better in case of REST based WCF services?

We are working on developing a REST based WCF service. I was wondering if it is a good idea to always return objects from the service calls irrespective of the execution status.
If any exception would occur on the service side, then appropriate fields in that object would be populated with the exception details (error code & message), otherwise it will just have the error code field set to 0 indicating success. In our case the consumer of the service can be either Java or .NET.
In REST services we model communication, including communicating errors, on the HTTP protocol. For REST services built using WCF 4, use the WebFaultException to return error conditions from a service. This results in returning a response message to the client with the HTTP status indicating the disposition of the request.

Error Handling in WCF Rest 4.0 online template

I keep getting the 400 bad request if there is de-serialization issue / other errors. If i try to debug by setting a breakpoint in the method that gets called, it does not get hit, if there is a deserialization issue. How do I intercept this and tweak the response to give me more details.
I looked at some articles regarding webprotocolexception but I think the WCF Rest online Template and the starter kit or not the same. Is the starter kit like an add-on to the template?
thanks for your time.
Handling Exceptions in RESTful WCF Services is tough. Deserialization issues are the worst since no user code gets called. The framework handles the Exception and simply returns an error to the caller. There is a way to see those errors though. You have to configure tracing for WCF (via Web.config). Here’s a link describing the process as well as where to find the trace viewer on your machine:
Service Trace Viewer Tool (SvcTraceViewer.exe)
Unfortunately there's no way to tweak that behavior. For other Exceptions, though, you can implement a custom HttpBehavior (or HttpBehavior2 if you're using the REST Starter Kit) with a custom IErrorHandler implementation to handle the Exceptions.
Error 400 means bad request => it is picked up at WCF level and does not even reach the method. So you need to look at the request and if you are passing JSON, fast chance it is in wrong format.
I had a personal project that I implemented in WCF REST and had to battle with this error which was quite frustrating. Also error handling on the server and returning error codes to the client is atrocious since you cannot return text content and all I have is HTTP error code and error description (first line in the HTTP response). I will never ever use WCF REST again as it is a bodged implementation.

View underlying SOAP message using vb.net

I have a VB.NET web service that calls a third party web service. How can I view the SOAP message generated by .NET before it is sent to the third party web service and how can I see the SOAP response before it is serialized by .NET.
When creating a standalone EXE, I see the Reference.vb file that is automatically generated, but don't see a similar file when my project is a web service. I have found lots of C# code to do this, but none in VB.NET.
Edit - Fiddler and TCP loggers are great, but will not work for my purposes. I need to be able to access the raw SOAP messages from within the application so I can log them or modify them. I need to do more than just see the messages going back and forth.
You can use fiddler or a tcp sniffer to filter and identify all outgoing and incoming traffic on your host.
This is if you want to see the xml request and response.
How about using an extension to allow you to examine the SOAP message?
Accessing Raw SOAP Messages in ASP.NET Web Services
http://msdn.microsoft.com/en-us/magazine/cc188761.aspx
I was trying to do the same thing and this seems to work for me:
Dim message As String = OperationContext.Current.RequestContext.RequestMessage.ToString()
I didn't think it would be that easy since most of the time ToString() returns the name of the class, but I tried it out and low and behold.
I know you asked this back in January so if since then you've figured out a better way let me know.
Please note that if you're catching the exception in a class that implements IErrorHandler then you have to perform this operation from within the ProvideFault() method instead of the HandleError() method because the context is closed before it gets to call the HandleError() method.
Hope this helps.