Error handling in node.js data access layer
Say I'm using a Repository pattern for data access as below:
#userController.coffee
# `userId` is obtained from the session
user =
email: 'Bob'
password: 'Secret'
db.userRepo(@userId).create user, (err, data) =>
# return results in http response or socket.io
This is what can go wrong during this method invocation:
user
has validation errors such as missing fields, etc. user.email
. My question is how to return each of these errors in the callback?
Options for callback arguments:
(err, data)
- where err
is an array of all errors encountered. (err, data)
- where err
is validation errors and database errors are thrown as exceptions. (err, data)
- same as above except when the user
already exists it returns null, because this is not an error but expected behaviour. (err, data, validation)
- where validation
is an array of validation errors or null
. (err, data, model)
- returning a model class with a validation property - active-record style. Feel free to propose something different.
Follow-up question: Where should validation of arguments take place? At the controller/routing level, data access level, or SQL database?
I'm planning on using a combination of node-validator and revalidator to validate objects and arguments.
Backstory: I have just moved over from Scala/Play to Node/Express for reasons of larger community, good web-sockets support, and developer productivity. After starting out with the Sequelize ORM I decided it was too constraining, had trouble with creating joins and my schema was simple anyway, so I started writing raw SQL. After an initial boost in development speed, I'm finding myself wanting static-typing back everyday. The number of tests and validation code I am writing is significantly larger.
我建议(err, data, validation)
以便您可以轻松检查用户需要重新输入的无效输入,以及实际的数据库错误err
,这可能会在写入日志文件的详细信息期间输出错误消息测试和原型。
上一篇: MVC混淆逻辑的放置位置。
下一篇: 在node.js数据访问层中处理错误