From 58c24c3c578762bfe7759fa8b98fa6dbdc8ed587 Mon Sep 17 00:00:00 2001 From: Afshin Arani Date: Tue, 25 Apr 2023 15:08:07 +0330 Subject: [PATCH] WorkflowGuidelines: add exception parsing --- docs/WorkflowGuidelines.md | 40 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/docs/WorkflowGuidelines.md b/docs/WorkflowGuidelines.md index 675006f1f..a2dcdd223 100644 --- a/docs/WorkflowGuidelines.md +++ b/docs/WorkflowGuidelines.md @@ -154,7 +154,47 @@ ``` This way, the code is more performant (even though this is the least important aspect), readable (as we can immediately see what is the potentially problematic variable) and maintainable (as new unexpected but unrelated exceptions can be generated by future versions of the library that contains the function called). + + * Avoid applying logic based on exception's message: + + Exception messages (even in stable libraries/softwares) are subject to change, applying logic based on the `Message` or `StackTrace` can cause hard-to-debug problems when updating your dependencies or .NET version. + Example: + ``` + try + let userObj = ctx.Public.Users.Create() + userObj.Id <- 1 + userObj.Name <- "Alice" + ctx.SubmitUpdates() + () + with + | :? PostgresException as ex when + ex.MessageText.Contains "duplicate key value" -> + Console.WriteLine "Primary key violation was detected when adding a new user:" + Console.WriteLine (ex.ToString()) + () + ``` + + Improved code: + ``` + // Returns true if exception indicates uniqueness problem + let isDuplicatePrimaryKeyError(ex: PostgresException) = + let uniqueViolationErrorCode = "23505" + ex.SqlState = uniqueViolationErrorCode + + try + let userObj = ctx.Public.Users.Create() + userObj.Id <- 1 + userObj.Name <- "Alice" + ctx.SubmitUpdates() + () + with + | :? PostgresException as ex when + isDuplicatePrimaryKeyError ex -> + Console.WriteLine "Primary key violation was detected when adding a new user:" + Console.WriteLine (ex.ToString()) + () + ``` * Not benefiting from your type system: