我们有一个图像上传页面,如果用户的上传时间超过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是否是一个超时异常,ala类似于:
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.";
}发布于 2022-02-08 20:48:43
您可以通过以下方法捕获几个超时条件:
bool IsTimeout(HttpException httpex)
{
switch ((HttpStatusCode)httpex.GetHttpCode())
{
case HttpStatusCode.RequestTimeout: //408
case HttpStatusCode.GatewayTimeout: //504
return true;
default: return false;
}
}发布于 2015-11-05 18:18:30
你需要用
ex.getType() is subClassException因为TimeoutException是一个子类。如果这是一次可能的投掷,那将是如何捕捉到这种类型的释放.
尽管如此,即使已经超时(请参阅https://msdn.microsoft.com/en-us/library/system.web.httprequest(v=vs.110).aspx ),仍然会抛出httpexpection。所以你需要做一些类似的事情
if(e.Message.Contains("timed out"))
//Do something because it timed outhttps://stackoverflow.com/questions/33551437
复制相似问题