Skip to content

Instantly share code, notes, and snippets.

@isaacabraham
Created April 15, 2019 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaacabraham/7e18d879e53ee1df41924870bdbe8db4 to your computer and use it in GitHub Desktop.
Save isaacabraham/7e18d879e53ee1df41924870bdbe8db4 to your computer and use it in GitHub Desktop.
module DbExceptions
open System.Text.RegularExpressions
let (|GenericDbException|_|) (ex:exn) =
match ex with
| :? SqlException as ex -> Some(GenericDbException ex)
| _ -> None
[<AutoOpen>]
module private CustomPatterns =
let (|ExactSqlException|_|) = function
| GenericDbException ex -> Some(ExactSqlException(ex.Number, ex))
| _ -> None
let (|NamedSqlException|_|) messagePart ex =
match ex with
| GenericDbException ex when ex.Message.Contains messagePart ->
Some(NamedSqlException(ex.Number, ex))
| _ -> None
let (|PrimaryKeyException|_|) = function
| NamedSqlException "PRIMARY KEY" (2627, ex) -> Some(PrimaryKeyException ex)
| _ -> None
let (|ForeignKeyConstraint|_|) = function
| ExactSqlException (547, ex) -> Some (ForeignKeyConstraint ex)
| _ -> None
let (|UniqueKeyException|_|) = function
| NamedSqlException "UNIQUE KEY" ((2627, ex) | (2601, ex)) ->
Some(UniqueKeyException ex)
| _ -> None
let (|NullValueException|_|) (ex:exn) =
match ex with
| ExactSqlException (515, sqlEx) ->
let m = Regex.Match(sqlEx.Message, "'[^']+'")
if m.Success then Some(m.Value.Replace("'", "")) else None
| :? System.Data.NoNullAllowedException as dataEx -> Some (dataEx.Message.Split(''').[1])
| _ -> None
|> Option.map(fun field -> NullValueException(Some field, ex))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment