m.e*_*son 9 .net c# asp.net exception-handling exception
我经常遇到以下异常,这是由用户启动下载引起的,因此失败(或被取消):
错误消息:远程主机关闭了连接.错误代码是0x80072746.堆栈跟踪:在System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte []状态,Byte []标头,Int32 keepConnected,Int32 totalBodySize,Int32 numBodyFragments,IntPtr [] bodyFragments,Int32 [] bodyFragmentLengths,Int32 doneWithSession,Int32 finalStatus,Boolean& System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean finalFlush)at System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean isFinal)atync)
我在互联网上搜索过,发现了一篇有趣的文章,但似乎没有一个明确的答案,因为这是防止这种填充日志的最佳方法.
用户没有看到任何错误,并且在应用程序中没有实际问题,因为它仅在我的理解中发生(在我的理解下)在其无法控制的情况下(用户取消下载或丢失连接)但是必须有一种方法来防止这样的异常报道.
我不想这么说但是我很想检查这个异常并且空了阻止它的屁股 - 但这让我觉得自己像个肮脏的程序员.
那么 - 防止此异常填满我邮箱的可接受方法是什么?
当您尝试向客户端发送响应但它们已断开连接时,会发生此错误.您可以通过在Response.Redirect上设置断点或者将数据发送到客户端的任何位置来验证这一点,等待Visual Studio命中断点,然后在IE中取消请求(使用位置栏中的x).这应该导致错误发生.
要捕获错误,您可以使用以下内容:
try
{
Response.Redirect("~/SomePage.aspx");
Response.End();
}
catch (System.Threading.ThreadAbortException)
{
// Do nothing. This will happen normally after the redirect.
}
catch (System.Web.HttpException ex)
{
if (ex.ErrorCode == unchecked((int)0x80070057)) //Error Code = -2147024809
{
// Do nothing. This will happen if browser closes connection.
}
else
{
throw ex;
}
}
Run Code Online (Sandbox Code Playgroud)
或者在C#6中,您可以使用异常过滤器来防止不得不重新抛出错误:
try
{
Response.Redirect("~/SomePage.aspx");
Response.End();
}
catch (System.Threading.ThreadAbortException)
{
// Do nothing. This will happen normally after the redirect.
}
catch (System.Web.HttpException ex) when (ex.ErrorCode == unchecked((int)0x80070057))
{
// Do nothing. This will happen if browser closes connection.
}
Run Code Online (Sandbox Code Playgroud)
这是一个更好的调试体验,因为它将停止在语句上抛出异常,当前状态和所有局部变量保留而不是在catch块内的throw上.
您无法阻止远程主机关闭任何内容。
在某些协议中,这是正常的(或至少是可接受的)告别方式。
所以你必须处理这个特定的异常。
归档时间: |
|
查看次数: |
7371 次 |
最近记录: |