我们有一个图片上传页面,如果用户的上传时间超过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.";
}
2条答案
按热度按时间hlswsv351#
您可以使用以下命令捕获几个超时条件:
46scxncf2#
您需要使用
因为TimeoutException是一个子类。如果它是一个可能的抛出,这将是如何捕捉该类型的异常...
尽管如此,httpexpection总是会被抛出,即使它确实超时(请参考每个方法抛出的https://msdn.microsoft.com/en-us/library/system.web.httprequest(v=vs.110).aspx)。