[英]How can I retrieve passed exception from HttpResponseMessage(HttpStatusCode, Exception)
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 ) 根据以下网站,您可以将异常参数传递给HttpResponseMessage.CreateErrorResponse方法( https://msdn.microsoft.com/en-us/library/jj127064(v=vs.118).aspx )
My question is how can I retrieve the exception information from the HttpResponseMessage created by the CreateErrorResponse method. 我的问题是如何从CreateErrorResponse方法创建的HttpResponseMessage中检索异常信息。 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?
如果无法获取异常信息,那么将异常作为输入进行方法重载有什么意义呢?
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. 澄清我不想要的答案......我知道我可以在身体内容中传递一个定制的错误原因( http://weblogs.asp.net/fredriknormen/asp-net-web-api-异常处理 )但我真的很好奇如何使用HttpRequestMessageExtensions.CreateErrorResponse方法(HttpRequestMessage,HttpStatusCode, Exception )方法重载。
Example WebAPI Controller: 示例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);
}
}
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?
}
To get the error message from the HttpResponseMessage you have to get the HttpError object as shown below. 要从HttpResponseMessage获取错误消息,您必须获取HttpError对象,如下所示。 The HttpError object then contains the ExceptionMessage, ExceptionType, and StackTrace information.
然后,HttpError对象包含ExceptionMessage,ExceptionType和StackTrace信息。
if(!response.IsSuccessStatusCode){
HttpError error = response.Content.ReadAsAsync<HttpError>().Result;
}
you could try using 你可以尝试使用
response.EnsureSuccessStatusCode()
Which will throw an exception if a successful response code isn't received. 如果未收到成功的响应代码,则会抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.