首页 > 解决方案 > 抛出错误时是否应该在不同的存储过程中重用相同的错误号?

问题描述

我正在使用Giraffe框架在F#. Web 服务器根据客户端请求执行一些存储过程。当无法处理请求时,存储过程中会引发错误,我正在Giraffe像这样捕获错误:

try
     // parse request ...
    // data access and execute stored procdeure ...
with
| :? System.Data.SqlClient.SqlException as e ->
     match e.Number with
    | 60000 ->
        return! (setStatusCode 400 >=> json e.Message) next ctx

假设在存储过程A中,我抛出了一个错误号60000,错误消息Error in stored procedure A。在另一个存储过程B中,我可以使用不同的错误消息重用相同的错误号还是应该使用不同的错误号?

如果我不重复使用相同的错误号,match表达式将继续增长,如下所示:

  with
  | :? System.Data.SqlClient.SqlException as e ->
            match e.Number with
            | 60000 ->
                return! (setStatusCode 400 >=> json e.Message) next ctx
            | 60001 ->
                return! (setStatusCode 400 >=> json e.Message) next ctx
            // more error numbers in the future ...

标签: sql-serverf#throw

解决方案


我实际上从未在 SQL 中使用过错误代码,所以我不知道什么是最佳实践,但我敢打赌它使用一个代码来处理一种类型的错误和一条消息。您的建议是弯曲该建议,其唯一目的是使代码的另一部分更短。

即使您确实创建了很多错误代码,您也可以通过这样做来避免代码中的重复

try ...
with
| :? SqlException as e ->
    match e.Number with
    | 60000 | 60001 ->
        return! (setStatusCode 400 >=> json e.Message) next ctx

如果这是您需要在多个地方执行的操作,请考虑将其拉出到它自己的单独功能中。如果错误代码列表变大,请考虑将其放入列表对象中,例如

open System.Linq

let sqlErrorCodes = [ 60000; 60001 ]

try ...
with :? SqlException e when sqlErrorCodes.Contains(e.Number) ->
    return! (setStatusCode 400 >=> json e.Message) next ctx

推荐阅读