Active pattern to extract HttpStatusCode from WebException

A simple active pattern that allows you to match WebExceptions by HttpStatusCode. I find it useful for quick scripts where I only need WebClient and don't have to get involved with WebRequest etc.

Copy Source
Copy Link
Tools:

Active pattern

1: let (|HttpException|_|) (ex:Exception) =
2:     match ex with
3:     | :? WebException as webException ->
4:         match webException.Response with
5:         | :? HttpWebResponse as response ->
6:             Some response.StatusCode
7:         | _ -> None
8:     | _ -> None

Example usage

 1: let fetch url = 
 2:     let webClient = new WebClient()
 3:     let rec get (url:string) =
 4:         try
 5:             Some (webClient.DownloadString(url))
 6:         with
 7:             | HttpException HttpStatusCode.Unauthorized ->
 8:                 webClient.Credentials <- getBetterCredentials
 9:                 get url
10:             | HttpException statusCode ->
11:                 printfn "Failed, server said: %A" statusCode
12:                 None
13:     get url
val ex : Exception

  type: Exception
  implements: Runtime.Serialization.ISerializable
  implements: Runtime.InteropServices._Exception
type Exception =
  class
    new : unit -> System.Exception
    new : string -> System.Exception
    new : string * System.Exception -> System.Exception
    member Data : System.Collections.IDictionary
    member GetBaseException : unit -> System.Exception
    member GetObjectData : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> unit
    member GetType : unit -> System.Type
    member HelpLink : string with get, set
    member InnerException : System.Exception
    member Message : string
    member Source : string with get, set
    member StackTrace : string
    member TargetSite : System.Reflection.MethodBase
    member ToString : unit -> string
  end

Full name: System.Exception

  type: Exception
  implements: Runtime.Serialization.ISerializable
  implements: Runtime.InteropServices._Exception
type WebException =
  class
    inherit System.InvalidOperationException
    new : unit -> System.Net.WebException
    new : string -> System.Net.WebException
    new : string * System.Exception -> System.Net.WebException
    new : string * System.Net.WebExceptionStatus -> System.Net.WebException
    new : string * System.Exception * System.Net.WebExceptionStatus * System.Net.WebResponse -> System.Net.WebException
    member GetObjectData : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> unit
    member Response : System.Net.WebResponse
    member Status : System.Net.WebExceptionStatus
  end

Full name: System.Net.WebException

  type: WebException
  implements: Runtime.InteropServices._Exception
  implements: Runtime.Serialization.ISerializable
  inherits: InvalidOperationException
  inherits: SystemException
  inherits: exn
val webException : WebException

  type: WebException
  implements: Runtime.InteropServices._Exception
  implements: Runtime.Serialization.ISerializable
  inherits: InvalidOperationException
  inherits: SystemException
  inherits: exn
property WebException.Response: WebResponse
type HttpWebResponse =
  class
    inherit System.Net.WebResponse
    member CharacterSet : string
    member Close : unit -> unit
    member ContentEncoding : string
    member ContentLength : int64
    member ContentType : string
    member Cookies : System.Net.CookieCollection with get, set
    member GetResponseHeader : string -> string
    member GetResponseStream : unit -> System.IO.Stream
    member Headers : System.Net.WebHeaderCollection
    member IsMutuallyAuthenticated : bool
    member LastModified : System.DateTime
    member Method : string
    member ProtocolVersion : System.Version
    member ResponseUri : System.Uri
    member Server : string
    member StatusCode : System.Net.HttpStatusCode
    member StatusDescription : string
    member SupportsHeaders : bool
  end

Full name: System.Net.HttpWebResponse

  type: HttpWebResponse
  implements: IDisposable
  implements: Runtime.Serialization.ISerializable
  inherits: WebResponse
  inherits: MarshalByRefObject
val response : HttpWebResponse

  type: HttpWebResponse
  implements: IDisposable
  implements: Runtime.Serialization.ISerializable
  inherits: WebResponse
  inherits: MarshalByRefObject
union case Option.Some: 'T -> Option<'T>
property HttpWebResponse.StatusCode: HttpStatusCode
union case Option.None: Option<'T>
val fetch : string -> string option

Full name: Snippet.fetch
val url : string

  type: string
  implements: IComparable
  implements: ICloneable
  implements: IConvertible
  implements: IComparable<string>
  implements: seq<char>
  implements: Collections.IEnumerable
  implements: IEquatable<string>
val webClient : WebClient

  type: WebClient
  implements: ComponentModel.IComponent
  implements: IDisposable
  inherits: ComponentModel.Component
  inherits: MarshalByRefObject
type WebClient =
  class
    inherit System.ComponentModel.Component
    new : unit -> System.Net.WebClient
    member BaseAddress : string with get, set
    member CachePolicy : System.Net.Cache.RequestCachePolicy with get, set
    member CancelAsync : unit -> unit
    member Credentials : System.Net.ICredentials with get, set
    member DownloadData : string -> System.Byte []
    member DownloadData : System.Uri -> System.Byte []
    member DownloadDataAsync : System.Uri -> unit
    member DownloadDataAsync : System.Uri * obj -> unit
    member DownloadFile : string * string -> unit
    member DownloadFile : System.Uri * string -> unit
    member DownloadFileAsync : System.Uri * string -> unit
    member DownloadFileAsync : System.Uri * string * obj -> unit
    member DownloadString : string -> string
    member DownloadString : System.Uri -> string
    member DownloadStringAsync : System.Uri -> unit
    member DownloadStringAsync : System.Uri * obj -> unit
    member Encoding : System.Text.Encoding with get, set
    member Headers : System.Net.WebHeaderCollection with get, set
    member IsBusy : bool
    member OpenRead : string -> System.IO.Stream
    member OpenRead : System.Uri -> System.IO.Stream
    member OpenReadAsync : System.Uri -> unit
    member OpenReadAsync : System.Uri * obj -> unit
    member OpenWrite : string -> System.IO.Stream
    member OpenWrite : System.Uri -> System.IO.Stream
    member OpenWrite : string * string -> System.IO.Stream
    member OpenWrite : System.Uri * string -> System.IO.Stream
    member OpenWriteAsync : System.Uri -> unit
    member OpenWriteAsync : System.Uri * string -> unit
    member OpenWriteAsync : System.Uri * string * obj -> unit
    member Proxy : System.Net.IWebProxy with get, set
    member QueryString : System.Collections.Specialized.NameValueCollection with get, set
    member ResponseHeaders : System.Net.WebHeaderCollection
    member UploadData : string * System.Byte [] -> System.Byte []
    member UploadData : System.Uri * System.Byte [] -> System.Byte []
    member UploadData : string * string * System.Byte [] -> System.Byte []
    member UploadData : System.Uri * string * System.Byte [] -> System.Byte []
    member UploadDataAsync : System.Uri * System.Byte [] -> unit
    member UploadDataAsync : System.Uri * string * System.Byte [] -> unit
    member UploadDataAsync : System.Uri * string * System.Byte [] * obj -> unit
    member UploadFile : string * string -> System.Byte []
    member UploadFile : System.Uri * string -> System.Byte []
    member UploadFile : string * string * string -> System.Byte []
    member UploadFile : System.Uri * string * string -> System.Byte []
    member UploadFileAsync : System.Uri * string -> unit
    member UploadFileAsync : System.Uri * string * string -> unit
    member UploadFileAsync : System.Uri * string * string * obj -> unit
    member UploadString : string * string -> string
    member UploadString : System.Uri * string -> string
    member UploadString : string * string * string -> string
    member UploadString : System.Uri * string * string -> string
    member UploadStringAsync : System.Uri * string -> unit
    member UploadStringAsync : System.Uri * string * string -> unit
    member UploadStringAsync : System.Uri * string * string * obj -> unit
    member UploadValues : string * System.Collections.Specialized.NameValueCollection -> System.Byte []
    member UploadValues : System.Uri * System.Collections.Specialized.NameValueCollection -> System.Byte []
    member UploadValues : string * string * System.Collections.Specialized.NameValueCollection -> System.Byte []
    member UploadValues : System.Uri * string * System.Collections.Specialized.NameValueCollection -> System.Byte []
    member UploadValuesAsync : System.Uri * System.Collections.Specialized.NameValueCollection -> unit
    member UploadValuesAsync : System.Uri * string * System.Collections.Specialized.NameValueCollection -> unit
    member UploadValuesAsync : System.Uri * string * System.Collections.Specialized.NameValueCollection * obj -> unit
    member UseDefaultCredentials : bool with get, set
  end

Full name: System.Net.WebClient

  type: WebClient
  implements: ComponentModel.IComponent
  implements: IDisposable
  inherits: ComponentModel.Component
  inherits: MarshalByRefObject
val get : (string -> string option)
Multiple items
val string : 'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------

type string = String

Full name: Microsoft.FSharp.Core.string

  type: string
  implements: IComparable
  implements: ICloneable
  implements: IConvertible
  implements: IComparable<string>
  implements: seq<char>
  implements: Collections.IEnumerable
  implements: IEquatable<string>
Multiple overloads
WebClient.DownloadString(address: Uri) : string
WebClient.DownloadString(address: string) : string
active recognizer HttpException: Exception -> HttpStatusCode option

Full name: Snippet.( |HttpException|_| )
type HttpStatusCode =
  | Continue = 100
  | SwitchingProtocols = 101
  | OK = 200
  | Created = 201
  | Accepted = 202
  | NonAuthoritativeInformation = 203
  | NoContent = 204
  | ResetContent = 205
  | PartialContent = 206
  | MultipleChoices = 300
  | Ambiguous = 300
  | MovedPermanently = 301
  | Moved = 301
  | Found = 302
  | Redirect = 302
  | SeeOther = 303
  | RedirectMethod = 303
  | NotModified = 304
  | UseProxy = 305
  | Unused = 306
  | TemporaryRedirect = 307
  | RedirectKeepVerb = 307
  | BadRequest = 400
  | Unauthorized = 401
  | PaymentRequired = 402
  | Forbidden = 403
  | NotFound = 404
  | MethodNotAllowed = 405
  | NotAcceptable = 406
  | ProxyAuthenticationRequired = 407
  | RequestTimeout = 408
  | Conflict = 409
  | Gone = 410
  | LengthRequired = 411
  | PreconditionFailed = 412
  | RequestEntityTooLarge = 413
  | RequestUriTooLong = 414
  | UnsupportedMediaType = 415
  | RequestedRangeNotSatisfiable = 416
  | ExpectationFailed = 417
  | InternalServerError = 500
  | NotImplemented = 501
  | BadGateway = 502
  | ServiceUnavailable = 503
  | GatewayTimeout = 504
  | HttpVersionNotSupported = 505

Full name: System.Net.HttpStatusCode

  type: HttpStatusCode
  inherits: Enum
  inherits: ValueType
field HttpStatusCode.Unauthorized = 401
property WebClient.Credentials: ICredentials
val getBetterCredentials : NetworkCredential

Full name: Snippet.getBetterCredentials

  type: NetworkCredential
  implements: ICredentials
  implements: ICredentialsByHost
val statusCode : HttpStatusCode

  type: HttpStatusCode
  inherits: Enum
  inherits: ValueType
val printfn : Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn

More information

Link: http://fssnip.net/9A
Posted: 2 years ago
Author: Leaf Garland
Tags: active pattern, exception, WebClient