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:

  • An error accessing the database
  • A syntax error in the query
  • Breaking a constraint (I'm using node-mysql) during a mutative query
  • A user has validation errors such as missing fields, etc.
  • A user already exists with 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?

  • At both levels there would be a lot of duplication of code. I would prefer to be DRY.
  • With static-typing I would detect bugs at the controller level and could trust the type system. Without static-typing the data layer cannot really trust anyone so it probably needs to have all validation logic.
  • Errors that would normally be picked up by static type-checking should throw errors because I need to fix them. They are bugs. However, if I do not find them, I would prefer to give the user a pleasant message, rather than an Internal Server Error 500 or a stack-trace.
  • If I wanted to evolve this into a public API, I will definitely need all the validation.
  • 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 ,这可能会在写入日志文件的详细信息期间输出错误消息测试和原型。

    链接地址: http://www.djcxy.com/p/67106.html

    上一篇: MVC混淆逻辑的放置位置。

    下一篇: 在node.js数据访问层中处理错误