数据库异常处理最佳实践 [英] Database exception handling best practices

查看:204
本文介绍了数据库异常处理最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何处理应用程序中的数据库异常?

您是否尝试在将数据传递给DB之前验证数据,或者只是依靠数据库模式验证逻辑?

从某些类型的数据库错误中恢复(例如超时)?

How do you handle database exceptions in your application?
Are you trying to validate data prior passing it to DB or just relying on DB schema validation logic?
Do you try to recover from some kind of DB errors (e.g. timeouts)?

这里有一些方法:


  1. 在将数据传递给DB之前验证数据

  2. 正确验证DB并正确处理数据库异常

  3. >
  4. 验证业务逻辑中的一些明显的约束,并将复杂的验证留给DB

您使用什么方法?为什么?

What approach do you use? Why?

更新

我很高兴看到越来越多的讨论。

让我们总结社区的答案。

I'm glad to see growing discussion.
Let’s try to sum up community answers.

建议:

  • Validate on both sides
  • Check business logic constraints on client side, let DB do integrity checks from hamishmcn
  • Check early to avoid bothering DB from ajmastrean
  • Check early to improve user experience from Will
  • Keep DB interacting code in place to simplify development from hamishmcn
  • Object-relational mapping (NHibernate, Linq, etc.) can help you to deal with constrains from ajmastrean
  • Client side validation is necessary for security reasons from Seb Nilsson

你还有什么要说的吗?这将转换为验证特定问题。我们缺少的核心,即数据库相关的错误最佳实践哪些要处理和哪些去泡沫?

Do you have anything else to say? This is converted to Validation specific question. We are missing the core, i.e. "Database related Error best practices" which ones to handle and Which ones to Bubble up?

推荐答案

@aku:DRY是好的,但它不总是可能的。验证是这些地方之一,因为您将有三个完全不同的和不相关的地方,其中验证不仅是可能的,而且绝对需要:在UI内,在业务逻辑内和数据库内。

@aku: DRY is nice, but its not always possible. Validation is one of those places, as you will have three completely different and unrelated places where validation is not only possible but absolutely needed: Within the UI, within the business logic, and within the database.

想一下web应用程序。您希望减少对服务器的访问,以便包括对客户端数据输入的JavaScript验证。但是您不能相信用户输入的内容,因此您必须在触摸数据库之前在业务逻辑中执行验证。并且数据库必须有自己的验证,以防止数据损坏。

Think of a web application. You want to reduce trips to the server, so you include javascript validation of client data entry. But you can't trust what the user enters, so you must perform validation within your business logic before touching the database. And the database must have its own validation in order to prevent data corruption.

没有干净的方法可以在一个组件中统一这三种不同类型的验证。

There's no clean way to unify these three different types of validation within a single component.

有一些尝试是为了统一横向责任,例如P& P组的 Policy Injection Application Block 以及验证应用程序块,但这些仍然基于代码。如果你的验证不在代码中,你仍然必须单独维护并行逻辑...

There are some attempts being made to unify cross-cutting responsibilities like validation within policy injectors like the P&P group's Policy Injection Application Block combined with their Validation Application Block, but these are still code based. If you have validation that's not in code, you still have to maintain parallel logic separately...

这篇关于数据库异常处理最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆