简体   繁体   中英

How can I retrieve the exception message from Request.CreateErrorResponse?

I have this code in my controller:

return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new Exception("Your cat is too small"));

In my calling code, I want to retrieve the Exception or at least the error. I wrote this code:

ObjectContent objContent = response.Content as ObjectContent;

The objContent is of type HttpError , so I pulled that out:

HttpError error = objContent.Value as HttpError;

But error seems to be a Dictionary with one value, key: Message, ValueL "An error has occurred"

I can't see any sign of the exception.

Assert.AreEqual("Your cat is too small", error["Message"]);

The assertion fails.

I used your code and reproduced the problem.

I wasn't able to step in to the .NET code to see why the Exception was being swallowed, so I had a look at the HttpRequestMessageExtensions source on GitHub and found that it passes the the Exception to a new HttpError object that is created from configuration (line 459).

I took the .NET code and doctored up the following to see what would happen.

private static HttpResponseMessage Test()
{
    HttpRequestMessage request = new HttpRequestMessage();

    return Test2(HttpStatusCode.InternalServerError, new Exception("Your cat is adequately sized."));
}

public static HttpResponseMessage Test2(HttpStatusCode statusCode, Exception exception)
{
    return Test2(statusCode, includeErrorDetail => new HttpError(exception, includeErrorDetail));
}

private static HttpResponseMessage Test2(HttpStatusCode statusCode, Func< bool, HttpError > errorCreator)
{
    HttpError r = errorCreator(false);
    return null;    
}

When I inspect the value of r , I can't see the Exception . If I change the value of the bool passed to errorCreator above to true . I can see much more detail when inspecting r .

I'm not great with the Web or Http namespaces, so you'll have to figure out how to pass true to that HttpError from the source on GH.

It doesn't directly answer the question, but hopefully it points you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM