Pauli Price
Pauli Price

Reputation: 4237

No ServiceStack WebServiceException.ResponseStatus on csv format request

When unit testing, I want to check csv formatted results, so I have the following code in my test.

MyDtoReq request = new MyDtoReq();
// ... assign some properties
string url = request.ToUrl("GET");
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
httpReq.Accept = "text/csv";
csv = new StreamReader(httpReq.GetResponse().GetResponseStream()).ReadToEnd();

That works fine, if the request succeeds. But when it fails, it raises a System.Net.WebException that doesn't have the expected WebServiceException.ResponseStatus details. NUnit reports the exception as follows:

Test Name:  TestReq
Test FullName:  [...].TestReq
Test Source:    c:\Users\[...]\UnitTestProject1\ServiceTests.cs : line 261
Test Outcome:   Failed
Test Duration:  0:00:27.104

Result Message: System.Net.WebException : The remote server returned an error: (400) Bad Request.
Result StackTrace:  at [...].TestReq() in c:\Users\[...]\UnitTestProject1\ServiceTests.cs:line 287

Turns out that this is by design, as most clients requesting csv format are not able to parse a ResponseStatus. In order to see the actual error, I would re-submit the request with format=html in the browser - a frustrating waste of time.

Upvotes: 1

Views: 704

Answers (1)

Pauli Price
Pauli Price

Reputation: 4237

Here's how to get the actual error message from failing csv format requests:

// Declared in test setup
public const string Host = "http://localhost:1337";
private const string BaseUri = Host + "/";

[Test]
public void TestMyDtoReqCsvFormat()
{
    MyDtoReq request = new MyDtoReq();
    request.startDate = "20130919";
    request.endDate = "20130930";
    request.source = "Token";

    try
    {
        string requestUrl = request.ToUrl("GET");
        HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(requestUrl);
        httpReq.Accept = "text/csv";
        var csv = new StreamReader(httpReq.GetResponse().GetResponseStream()).ReadToEnd();
        // assert some facts about the contents of csv
    }
    catch (Exception)
    {
        try {
            JsonServiceClient client = new JsonServiceClient(BaseUri);
            MyDtoReqResponse response = client.Get(request);
            // do something if re-request succeeds (i.e. was a transient error)
        }
        catch (WebServiceException webEx) 
        {
            var message = webEx.ResponseStatus.ErrorCode +
                " " + webEx.ResponseStatus.Message.Trim() +
                " " + webEx.ResponseStatus.StackTrace.Trim();
            throw new WebException(message,webEx);
        }
        catch (Exception otherEx) {
            System.Diagnostics.Debug.WriteLine(otherEx.Message);
            throw new Exception(otherEx.Message, otherEx);
        }
    }
}

Upvotes: 1

Related Questions