如果代理服务器不可用,则会正常处理错误

时间:2018-03-31 09:17:08

标签: f#

我的代码中有一个指定的代理,如果代理服务器没有运行,我希望能够正常处理错误。我正在使用Charles代理。

let request = WebRequest.CreateHttp(Uri url)
request.Proxy <- WebProxy("localhost", 8888)
request.Method <- "GET"

async {
    try
        use! response = request.AsyncGetResponse()
        use stream = response.GetResponseStream()
        use reader = new StreamReader(stream)
        return Ok (reader.ReadToEnd())
    with :? WebException as e -> 
        use response = e.Response :?> HttpWebResponse
        use stream = response.GetResponseStream() // error
        use streamReader = new StreamReader(stream)
        use memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(streamReader.ReadToEnd()))
        // use memoryStream
        return Error {Status = response.StatusCode}
}

如果代理服务器不可用,则以下行会引发错误。我怎样才能优雅地处理这种情况?

use stream = response.GetResponseStream()
  

System.NullReferenceException:未将对象引用设置为对象的实例。

1 个答案:

答案 0 :(得分:1)

WebException.Result表示

  

如果响应可用来自Internet资源,则为WebResponse   包含来自Internet资源的错误响应的实例;   否则,null

这意味着您的行

use response = e.Response :?> HttpWebResponse

导致null因为没有可用的响应。这是有道理的,因为应该发送请求的代理不可用。

您可以使用函数isNull来检查空值,例如

let request = WebRequest.CreateHttp(Uri url)
request.Proxy <- WebProxy("localhost", 8888)
request.Method <- "GET"

async {
    try
        use! response = request.AsyncGetResponse()
        use stream = response.GetResponseStream()
        use reader = new StreamReader(stream)
        return Ok (reader.ReadToEnd())
    with :? WebException as e -> 
        use response = e.Response :?> HttpWebResponse
        if isNull(response) then
            return Error {Status = response.StatusCode}
        else
            use stream = response.GetResponseStream() // error
            use streamReader = new StreamReader(stream)
            use memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(streamReader.ReadToEnd()))
            // use memoryStream
            return Error {Status = response.StatusCode}
}