Throwing a fault inside a behavior and returning it to client

547 views Asked by At

I'm writing some services in WCF to be called by a Silverlight client. I change status code to 200 every time a fault is to be returned, via a IDispatchMessageInspector.

It works almost perfect, but sometimes it keeps returning error 500: NotFound.

I have just written another IDispatchMessageInspector to commit changes in a ObjectContext. But when this fails, the error handler is not called.

I think by the time UnitOfWorkMessageInspector runs, the message was already been set up as a non-fault-response. How can I do both things work?

    public class UnitOfWorkMessageInspector : IDispatchMessageInspector
    {
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (!reply.IsFault)
            {
                try
                {
                    UnitOfWorkBase.Commit();
                }
                catch (OptimisticConcurrencyException)
                {
                    throw new FaultException("It was changed by another user. Try again.");
                }
            }
        }
2

There are 2 answers

0
André Werlang On BEST ANSWER

I managed to make it work. I figured out my IDispatchMessageInspector for switching from status code 500 to 200 wouldn't work because the message was already built, then I replaced the message.

    public class UnitOfWorkMessageInspector : IDispatchMessageInspector
    {
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (!reply.IsFault)
            {
                try
                {
                    UnitOfWorkBase.Commit();
                }
                catch (OptimisticConcurrencyException)
                {
                    FaultException fe = new FaultException("It was changed by another user. Try again.");
                    reply = Message.CreateMessage(reply.Version, fe.CreateMessageFault(), fe.Action);
                }
            }
        }
3
Shiraz Bhaiji On

Code 500 is Internal Error.

Some error is occuring and it is not caught on the server side.

In your code you only catch OptimisticConcurrencyException you need to also catch Exception.