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

时间:2015-03-04 21:36:46

标签: 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-exception-handling),但我真的很好奇如何使用 HttpRequestMessageExtensions.CreateErrorResponse方法(HttpRequestMessage,HttpStatusCode,异常) 方法重载。

示例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);
        }
    }

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

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?
    }

2 个答案:

答案 0 :(得分:9)

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

if(!response.IsSuccessStatusCode){
    HttpError error = response.Content.ReadAsAsync<HttpError>().Result;
}

答案 1 :(得分:6)

您可以尝试使用

 response.EnsureSuccessStatusCode()

如果未收到成功的响应代码,则会引发异常。