Guidance on Error Reporting to Caller

Topics: Web Api
May 5, 2011 at 4:50 PM

If I have following resource defined:

    [ServiceContract]
    public class TransactionResource
    {

        [WebInvoke(UriTemplate = "/initiate", Method = "POST")]
        public HttpResponseMessage<Transaction> Initiate(HttpRequestMessage<Transaction> req)
        {
            req.Content.ContentReadStream.Position = 0;
            Transaction info = req.Content.ReadAs<Transaction>();
            HttpResponseMessage<Transaction> resp = new HttpResponseMessage<Transaction>(info);
            if (info.TransactionId != 0)
            {
                       //Http Status Code: Bad Request (400)
                      //<Errors>
                      //    <Error>
                      //        <Id>1</Id>
                      //        <Message>Transaction id must be zero.<Message>
                      //    </Error>
                      //</Errors>
            }

            info.TransactionId = 1;
            info.TransactionCode = "ABCDEF";
            info.CreateDate = DateTime.Now;

            resp.StatusCode = System.Net.HttpStatusCode.Created;

            return resp;
        }
    }

In the above code, if the transaction id is not zero, I would like to set the response status code to 400 (Bad Request). In addition, I would like to send error information in a formal structure of Error. Obviously the error format will differ based on the Accept header. So it could be xml or json or whatever. Setting the status code is easy. But not sure how to send the error info.

First I thought I could do this by throwing HttpResponseException by passing HttpResponseMessage<Error> in the constructor. But HttpResponseException only takes HttpResponseMessage type and not HttpResponseMessage<T>.

What is the best way to do this?

May 5, 2011 at 5:45 PM

HttpRepsonseMessage<T> derives from HttpResponseMessage so there should be no problem passing it into the HttpResponseException constructor.

May 5, 2011 at 10:13 PM
DarrelMiller wrote:

HttpRepsonseMessage<T> derives from HttpResponseMessage so there should be no problem passing it into the HttpResponseException constructor.


This.  And as long as you have media type formatters setup to handle all the cases you might see from accept headers, you should be good to go.