Javascript 快速错误处理模式

Javascript 快速错误处理模式,javascript,express,ecmascript-6,es6-promise,Javascript,Express,Ecmascript 6,Es6 Promise,我正在研究Express以创建一个简单的JSON API,但我不确定如何组织输入参数验证和错误处理。错误可能源于验证步骤,也可能源于数据库访问步骤。这就是我到目前为止所做的: router.use(function(req, res, next) { validate(req.query).then(function() { next() }).catch(function(e) { next(e) }) }) router.get("/

我正在研究Express以创建一个简单的JSON API,但我不确定如何组织输入参数验证和错误处理。错误可能源于验证步骤,也可能源于数据库访问步骤。这就是我到目前为止所做的:

router.use(function(req, res, next) {
    validate(req.query).then(function() {
        next()
    }).catch(function(e) {
        next(e)
    })
})

router.get("/", function(req, res, next) {
    someDatabaseAccess(req.query).then(function(results) {
        res.json(results)
    }).catch(function(e) {
        next(e)
    })
})

router.use(function(e, req, res, next) {

    // ... (handling specific errors)

    res.status(400)
    res.json(someDummyResponse(e))
})
验证如下所示:

const validate = function(q) {
    return new Promise(function(resolve, reject) {
        if (q.someParameter) {
            if (somethingWrong(q.someParameter)) {
                reject(new Error("Something wrong!"))
            }
        }
        resolve()
    })
}

这有意义吗?是否有什么我应该做的不同/以一种不太复杂的方式?

为了验证,我建议看看工具。 例如,我使用包作为验证器,但有很多类似的。首先创建对象的架构:

const tv4 = require('tv4');

const schema = {
  type: object,
  properties: {
    name: string,
    phone: string
  },
  required: ['name']
};
然后在您的路线中,您会:

app.post('/someroute', (req, res, next) => {
  if (!tv4.validate(req.body, schema) ) 
    return next( new Error('not valid input'));
  // do some cool stuff here
  res.end();
});
express中的错误处理基本上是添加一个中间件函数作为最后一个,并带有附加参数:

// add middleware
app.use(bodyParser.json())

// add custom middleware
app.use(function(req, res, next) {
  // some cool stuff
  next();
});    

// add routes
app.get('/', () => {})

// error handler always last
// Pay attention to additional `err` param
app.use(function (err, req, res, next) {
  if (err) {
    // log error, whatever handling logic
  }
  else next();
});

为了验证,我建议看一下工具。 例如,我使用包作为验证器,但有很多类似的。首先创建对象的架构:

const tv4 = require('tv4');

const schema = {
  type: object,
  properties: {
    name: string,
    phone: string
  },
  required: ['name']
};
然后在您的路线中,您会:

app.post('/someroute', (req, res, next) => {
  if (!tv4.validate(req.body, schema) ) 
    return next( new Error('not valid input'));
  // do some cool stuff here
  res.end();
});
express中的错误处理基本上是添加一个中间件函数作为最后一个,并带有附加参数:

// add middleware
app.use(bodyParser.json())

// add custom middleware
app.use(function(req, res, next) {
  // some cool stuff
  next();
});    

// add routes
app.get('/', () => {})

// error handler always last
// Pay attention to additional `err` param
app.use(function (err, req, res, next) {
  if (err) {
    // log error, whatever handling logic
  }
  else next();
});

更结构化的方法是使用一个单独的错误配置文件,并使用中间件抛出该错误,这样应用程序的结构会更好

error.json

"err":[
   "errorLog501":{
     "status":501,
     "message":"request is invalid"
    }
]
`


在JSON响应中传递状态代码非常重要,这样前端可以显示适当的错误消息,用户可以知道应用程序的状态。更结构化的方法是使用单独的错误配置文件,并使用中间件抛出错误,这样应用程序的结构会更好

error.json

"err":[
   "errorLog501":{
     "status":501,
     "message":"request is invalid"
    }
]
`

在JSON响应中传递状态代码非常重要,这样前端可以显示适当的错误消息,用户可以知道应用程序的状态