我们有一个图片上传页面,如果用户上传的时间超过15分钟,该页面会超时。
我们正在捕获超时发生的HttpException。但是我们怎么知道由于超时而发生异常,所以我们可以返回一条特定的消息?
我们的代码:
try
{
// do stuff here
}
catch (HttpException ex)
{
// What can we check to know if this is a timeout exception?
// if (ex == TimeOutError)
// {
// return "Took too long. Please upload a smaller image.";
// }
return "Error with image. Try again.";
}
catch (Exception ex)
{
return "Error with image. Try again.";
}
超时错误是什么样的:
System.Web.HttpException (0x80004005): Request timed out.
at System.Web.HttpRequest.GetEntireRawContent()
at System.Web.HttpRequest.GetMultipartContent()
at System.Web.HttpRequest.FillInFormCollection()
at System.Web.HttpRequest.EnsureForm()
at System.Web.HttpRequest.get_Form()
at MyStore.upload.ProcessRequest(HttpContext context)
ex.ErrorCode=-2147467259
ex.GetHttpCode=500
ex.WebEventCode=0
我只是想做一个比较上面错误代码的if
语句而犹豫不决。
HttpCode 500
似乎是一个通用Internal Server Error
代码,可能不仅仅是超时异常。
ErrorCode -2147467259
是我不熟悉的。如果该数字对于超时错误保持不变,并且在非超时异常时永远不会发生,那么我可以对此数字进行if
比较。
我认为必须有一种简单的方法来了解HttpException
是否是超时异常,例如:
if (ex == TimeoutError) // what should this be?
更新
我刚刚尝试捕获TimeoutException
,如下所示,但它仍然只被HttpException
捕获。
try
{
// do stuff here
}
catch (TimeoutException ex)
{
// Timeout doesn't get caught. Must be a different type of timeout.
// So far, timeout is only caught by HttpException.
return "Took too long. Please upload a smaller image.";
}
catch (HttpException ex)
{
// What can we check to know if this is a timeout exception?
// if (ex == TimeOutError)
// {
// return "Took too long. Please upload a smaller image.";
// }
return "Error with image. Try again.";
}
catch (Exception ex)
{
return "Error with image. Try again.";
}
答案 0 :(得分:0)
您需要使用
ex.getType() is subClassException
由于TimeoutException是一个子类。如果这是一种可能的抛出,那将是如何捕捉这种类型的执行......
虽然,即使确实超时,也总会抛出httpexpection(从每个方法抛出的内容中引用https://msdn.microsoft.com/en-us/library/system.web.httprequest(v=vs.110).aspx)。所以你需要做类似的事情,
if(e.Message.Contains("timed out"))
//Do something because it timed out