Csharp/C#教程:正确处理两个WebException分享


正确处理两个WebException

我正在尝试正确处理两个不同的WebException

基本上他们在调用WebClient.DownloadFile(string address, string fileName)

到目前为止,AFAIK有两个我要处理的,都是WebException的:

可能会有更多,但这是我迄今为止最重要的。

那么我应该如何正确处理它,因为它们都是WebException ,但我想以不同的方式处理上面的每个案例。

这是我到目前为止:

 try { using (var client = new WebClient()) { client.DownloadFile("..."); } } catch(InvalidOperationException ioEx) { if (ioEx is WebException) { if (ioEx.Message.Contains("404") { //handle 404 } if (ioEx.Message.Contains("remote name could not") { //handle file doesn't exist } } } 

正如您所看到的,我正在检查消息以查看它是什么类型的WebException。 我会假设有更好或更精确的方法来做到这一点?

谢谢

根据这篇MSDN文章 ,您可以执行以下操作:

 try { // try to download file here } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound) { // handle the 404 here } } else if (ex.Status == WebExceptionStatus.NameResolutionFailure) { // handle name resolution failure } } 

我不确定WebExceptionStatus.NameResolutionFailure是您看到的错误,但您可以检查抛出的exception并确定该错误的WebExceptionStatus是什么。

上述就是C#学习教程:正确处理两个WebException分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1013253.html

(0)
上一篇 2021年12月30日
下一篇 2021年12月30日

精彩推荐