12 people like it.

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.

Active pattern

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

Example usage

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
let fetch url = 
    let webClient = new WebClient()
    let rec get (url:string) =
        try
            Some (webClient.DownloadString(url))
        with
            | HttpException HttpStatusCode.Unauthorized ->
                webClient.Credentials <- getBetterCredentials
                get url
            | HttpException statusCode ->
                printfn "Failed, server said: %A" statusCode
                None
    get url
val ex : Exception
Multiple items
type Exception =
  new : unit -> Exception + 2 overloads
  member Data : IDictionary
  member GetBaseException : unit -> Exception
  member GetObjectData : info:SerializationInfo * context:StreamingContext -> unit
  member GetType : unit -> Type
  member HelpLink : string with get, set
  member InnerException : Exception
  member Message : string
  member Source : string with get, set
  member StackTrace : string
  ...

Full name: System.Exception

--------------------
Exception() : unit
Exception(message: string) : unit
Exception(message: string, innerException: exn) : unit
Multiple items
type WebException =
  inherit InvalidOperationException
  new : unit -> WebException + 4 overloads
  member GetObjectData : serializationInfo:SerializationInfo * streamingContext:StreamingContext -> unit
  member Response : WebResponse
  member Status : WebExceptionStatus

Full name: System.Net.WebException

--------------------
WebException() : unit
WebException(message: string) : unit
WebException(message: string, innerException: exn) : unit
WebException(message: string, status: WebExceptionStatus) : unit
WebException(message: string, innerException: exn, status: WebExceptionStatus, response: WebResponse) : unit
val webException : WebException
property WebException.Response: WebResponse
type HttpWebResponse =
  inherit WebResponse
  member CharacterSet : string
  member Close : unit -> unit
  member ContentEncoding : string
  member ContentLength : int64
  member ContentType : string
  member Cookies : CookieCollection with get, set
  member GetResponseHeader : headerName:string -> string
  member GetResponseStream : unit -> Stream
  member Headers : WebHeaderCollection
  member IsMutuallyAuthenticated : bool
  ...

Full name: System.Net.HttpWebResponse
val response : HttpWebResponse
union case Option.Some: Value: 'T -> Option<'T>
property HttpWebResponse.StatusCode: HttpStatusCode
union case Option.None: Option<'T>
val fetch : url:string -> string option

Full name: Script.fetch
val url : string
val webClient : WebClient
Multiple items
type WebClient =
  inherit Component
  new : unit -> WebClient
  member BaseAddress : string with get, set
  member CachePolicy : RequestCachePolicy with get, set
  member CancelAsync : unit -> unit
  member Credentials : ICredentials with get, set
  member DownloadData : address:string -> byte[] + 1 overload
  member DownloadDataAsync : address:Uri -> unit + 1 overload
  member DownloadFile : address:string * fileName:string -> unit + 1 overload
  member DownloadFileAsync : address:Uri * fileName:string -> unit + 1 overload
  member DownloadString : address:string -> string + 1 overload
  ...

Full name: System.Net.WebClient

--------------------
WebClient() : unit
val get : (string -> string option)
Multiple items
val string : value:'T -> string

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

--------------------
type string = String

Full name: Microsoft.FSharp.Core.string
WebClient.DownloadString(address: Uri) : string
WebClient.DownloadString(address: string) : string
active recognizer HttpException: Exception -> HttpStatusCode option

Full name: Script.( |HttpException|_| )
type HttpStatusCode =
  | Continue = 100
  | SwitchingProtocols = 101
  | OK = 200
  | Created = 201
  | Accepted = 202
  | NonAuthoritativeInformation = 203
  | NoContent = 204
  | ResetContent = 205
  | PartialContent = 206
  | MultipleChoices = 300
  ...

Full name: System.Net.HttpStatusCode
field HttpStatusCode.Unauthorized = 401
property WebClient.Credentials: ICredentials
val getBetterCredentials : NetworkCredential

Full name: Script.getBetterCredentials
val statusCode : HttpStatusCode
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Raw view Test code New version

More information

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