如何从HttpResponseMessage中检索传递的异常(HttpStatusCode,异常) [英] How can I retrieve passed exception from HttpResponseMessage(HttpStatusCode, Exception)
问题描述
根据以下网站,您可以将异常参数传递给HttpResponseMessage.CreateErrorResponse方法( https://msdn.microsoft.com/zh-CN/library/jj127064(v = vs.118).aspx )
According to the following website, you can pass an exception parameter to the HttpResponseMessage.CreateErrorResponse method (https://msdn.microsoft.com/en-us/library/jj127064(v=vs.118).aspx)
我的问题是如何从CreateErrorResponse方法创建的HttpResponseMessage中检索异常信息。如果没有办法获取异常信息,那么有一个方法重载将异常作为输入有什么意义?
My question is how can I retrieve the exception information from the HttpResponseMessage created by the CreateErrorResponse method. If there is not way to get the exception information, what is the point of having a method overload for taking an exception as an input?
要澄清我的答案不寻找...
我知道我可以在正文内容中传递自定义错误原因( http://weblogs.asp.net/fredriknormen/asp-net-web-api-exception-handling ),但我真的很好奇如何使用 HttpRequestMessageExtensions.CreateErrorResponse方法(HttpRequestMessage,HttpStatusCode,异常)方法重载。
To clarify on what answers I am not looking for... I know that I can pass a customized error reason in the content of the body (http://weblogs.asp.net/fredriknormen/asp-net-web-api-exception-handling) but I am really just curious about how to use the HttpRequestMessageExtensions.CreateErrorResponse Method (HttpRequestMessage, HttpStatusCode, Exception) method overload.
示例WebAPI控制器:
Example WebAPI Controller:
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);
}
}
如何在此代码中获取异常:
How do I pick up the exception in this code:
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?
}
推荐答案
从以下位置获取错误消息HttpResponseMessage,您必须获取HttpError对象,如下所示。然后,HttpError对象包含ExceptionMessage,ExceptionType和StackTrace信息。
To get the error message from the HttpResponseMessage you have to get the HttpError object as shown below. The HttpError object then contains the ExceptionMessage, ExceptionType, and StackTrace information.
if(!response.IsSuccessStatusCode){
HttpError error = response.Content.ReadAsAsync<HttpError>().Result;
}
这篇关于如何从HttpResponseMessage中检索传递的异常(HttpStatusCode,异常)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!