sql-server - 抛出错误时是否应该在不同的存储过程中重用相同的错误号?
问题描述
我正在使用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 中使用过错误代码,所以我不知道什么是最佳实践,但我敢打赌它使用一个代码来处理一种类型的错误和一条消息。您的建议是弯曲该建议,其唯一目的是使代码的另一部分更短。
即使您确实创建了很多错误代码,您也可以通过这样做来避免代码中的重复
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
推荐阅读
- ios - 将现有的 C 库包装为框架
- coq - 关于我在 Coq 上的归纳类型的琐碎定理
- python - 如何安装 textatistic 包
- ruby-on-rails - 从关联模型(表)中查找至少具有一个关联的所有记录
- java - Java 中的主线程是否总是比任何其他新线程运行得更快?
- javascript - 为什么我不能在 JavaScript 中使用我的类方法访问我的类的属性?
- rust - 使用 web_sys 生成随机数数组
- ios - 如何循环通过日期范围?
- r - R 中的错误:我应该使用 rep() 但我已经这样做了
- python - 使用更多训练数据增强来自 HuggingFace 的 MarianMT 预训练模型