简体   繁体   English

快速错误处理模式

[英]Express error handling pattern

I'm looking into Express to create a simple JSON API, and I'm not sure how to organize my input parameter validation and error handling. 我正在研究Express来创建一个简单的JSON API,我不知道如何组织我的输入参数验证和错误处理。 Errors can originate from the validation step but also from the database access step. 错误可以来自验证步骤,也可以来自数据库访问步骤。 This is what I have so far: 这是我到目前为止:

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))
})

The validation looks like this: 验证看起来像这样:

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

Does this make sense? 这有意义吗? Is there anything I should do differently/in a less convoluted way? 有什么我应该做的不同/以一种不那么令人费解的方式?

To validate, I suggest to have a look at JSONSchema tools. 为了验证,我建议看一下JSONSchema工具。 For example, I use package tv4 as a validator, but there are lots of similar. 例如,我使用包tv4作为验证器,但有很多类似的。 First you create a schema of the object: 首先,您创建对象的模式:

const tv4 = require('tv4');

const schema = {
  type: object,
  properties: {
    name: string,
    phone: string
  },
  required: ['name']
};

Then in you route, you do: 然后在你的路线中,你做:

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();
});

The error handling in express is basically about adding a middleware function as a last one, and with additional params: 快递中的错误处理基本上是关于添加中间件函数作为最后一个,并使用其他参数:

// 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();
});

A more structured way would be to have a separate error config file and throw that error using a middleWare that way your app is better structured 更结构化的方法是使用单独的错误配置文件并使用中间件抛出该错误,这样您的应用程序的结构更好

error.json error.json

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

` `

var errCodes = require('./error.json')
var errMiddleware = function(req, res, next) {
   if (req.body.hello) {
   // some cool stuff
     res.json(errCodes.errorLog501)
   } else {
     next();
   }
}

app.use(errMiddleware); //everytime a request happens the middleware called

It is very Important to pass status code in JSON response so that the Frontend can display appropriate error messages and user can know the state of application 在JSON响应中传递状态代码非常重要,这样前端可以显示相应的错误消息,用户可以知道应用程序的状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM