如何从HttpResponseMessage检索传递的异常(HttpStatusCode,Exception)

geo*_*hnH 7 c# error-handling asp.net-web-api

根据以下网站,您可以将异常参数传递给HttpResponseMessage.CreateErrorResponse方法(https://msdn.microsoft.com/en-us/library/jj127064(v=vs.118).aspx)

我的问题是如何从CreateErrorResponse方法创建的HttpResponseMessage中检索异常信息.如果无法获取异常信息,那么将异常作为输入进行方法重载有什么意义呢?

澄清我不想要的答案......我知道我可以在身体内容中传递一个定制的错误原因(http://weblogs.asp.net/fredriknormen/asp-net-web-api-异常处理)但我真的很好奇如何使用HttpRequestMessageExtensions.CreateErrorResponse方法(HttpRequestMessage,HttpStatusCode,Exception)方法重载.

示例WebAPI控制器:

Route("location/{locationName}/Databases/{databasename}/ProcedureSession")][LocationSetUp]
public HttpResponseMessage Post([FromBody] ProcedureSessionData procedureSession)
    {
        try
        {
            throw new Exception("test Exception");
        }
        catch (Exception e)
        {
           return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
             e);
        }
    }
Run Code Online (Sandbox Code Playgroud)

如何在此代码中选择异常:

using (var client = new HttpClient())
  {
    client.BaseAddress = new Uri("http://localhost/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    string api = "testApi/location/here/databases/testDb/ProcedureSession";
    HttpResponseMessage response = client.PostAsJsonAsync(api, newSessionData).Result;
    if (!response.IsSuccessStatusCode)
    {
         //how can i pick up the exception object from here? 
         //Or am I missing the point of this CreateErrorResponse overload?
    }
Run Code Online (Sandbox Code Playgroud)

geo*_*hnH 9

要从HttpResponseMessage获取错误消息,您必须获取HttpError对象,如下所示.然后,HttpError对象包含ExceptionMessage,ExceptionType和StackTrace信息.

if(!response.IsSuccessStatusCode){
    HttpError error = response.Content.ReadAsAsync<HttpError>().Result;
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ney 6

你可以尝试使用

 response.EnsureSuccessStatusCode()
Run Code Online (Sandbox Code Playgroud)

如果未收到成功的响应代码,则会抛出异常.