Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.