捕获特定的WebException(550)
假设我创建并执行System.Net.FtpWebRequest
。
我可以使用catch (WebException ex) {}
来捕获此请求引发的任何与Web相关的exception。 但是如果我有一些逻辑,我只想在由于(550) file not found
引发exception时执行?
最好的方法是什么? 我可以复制exception消息并测试相等性:
const string fileNotFoundExceptionMessage = "The remote server returned an error: (550) File unavailable (eg, file not found, no access)."; if (ex.Message == fileNotFoundExceptionMessage) {
但从理论上讲,这条消息似乎可以改变。
或者,我可以测试以查看exception消息是否包含“550”。 如果消息被更改,这种方法可能更有效(它可能在文本中的某处仍然包含“550”)。 但是,如果某些其他WebException
的文本碰巧包含“550”,那么这样的测试当然也会返回true。
似乎没有一种方法可以只访问exception的数量 。 这可能吗?
WebException
公开您可以检查的StatusCode
属性。
如果您需要实际的HTTP响应代码,可以执行以下操作:
(int)((HttpWebResponse)ex.Response).StatusCode
作为参考,这是我最终使用的实际代码:
catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ((FtpWebResponse)ex.Response).StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { // Handle file not found here }
声明一个WebException对象,将Catch块中的ex值转换为它。 然后,您可以检查StatusCode属性。