[英]F#: System.Net.WebException
我是編程新手,F#是我的第一語言。 我目前對.NET API還是很陌生。
作為一個初學者的項目,我想抓取一個網站。 我想編寫一個函數,給定特定的URL,該函數將自動下載該頁面上的所有HTML內容。 但是,如果URL無效,而不是拋出System.Net.WebException消息,我想返回布爾輸出“ False”。
這是我的代碼的相關部分:
let noSuchURL (url: string) =
let html = downloadHtmlFromUrl url
let regexPattern = @"<title>Page not found</title>"
let matchResult = Regex.IsMatch(html, regexPattern)
matchResult
(我已經在F#交互中測試了downloadHtmlFromUrl函數,並且工作正常。)
我意識到上面的代碼在地址無效的情況下不會返回布爾值。 而是,拋出System.Net.WebException,並顯示消息“ System.Net.WebException:遠程服務器返回錯誤:(404)未找到”。
我可以進行哪些更改以獲得布爾輸出?
也許抓住例外?
let noSuchURL (url: string) =
try
let html = downloadHtmlFromUrl url
let regexPattern = @"<title>Page not found</title>"
let matchResult = Regex.IsMatch(html, regexPattern)
matchResult
with :? System.Net.WebException -> false
一個警告:如果存在WebException
,則該程序將返回false
,而不管引發該異常的原因如何。 如果要在404響應中專門返回false
,則必須仔細查看WebException
:
let noSuchURL (url: string) =
try
let html = downloadHtmlFromUrl url
let regexPattern = @"<title>Page not found</title>"
let matchResult = Regex.IsMatch(html, regexPattern)
matchResult
with
:? System.Net.WebException as e
when e.Status = WebExceptionStatus.ProtocolError ||
e.Status = WebExceptionStatus.NameResolutionFailure
-> false
有關F#中的異常的更多信息,請查看https://msdn.microsoft.com/zh-cn/library/dd233194.aspx 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.