如何处理Node.js / express中的错误

时间:2018-03-16 17:32:08

标签: javascript node.js express

我试图捕捉错误而不是扔掉它们。我试过尝试/捕获,但意识到这不起作用所以我有点松散的结局。这两个错误与mongodb有关,但我认为仍然会抛出node / express错误。

void MainWindow::on_commandLinkButton_clicked()
{
    QString file = QFileDialog::getSaveFileName(this,
                                                tr("Save Sprite file"),
                                                "",tr("File PNG (*.png)"));

    if(!file.isEmpty())
    {
        ui->SpriteFront->Composite();
        ui->SpriteFront->Composited.save(file,"PNG");
    }
}

如果我app.get( "/test/:lastName", function ( reqt, resp ) { var driverName = reqt.params.lastName mongoClient.connect( "mongodb://localhost/enteprise", function( err, db ) { if ( err ) { console.error("1 mess " + err) } var database = db.db( "enteprise" ) var collection = database.collection( "driversCol" ) collection.findOne( { lastName : driverName }, function( err, res ) { if ( err ) { console.error("2 mess " + err) } resp.json( res.rate ) db.close() }) }) }) 那么'43'应该按照费率返回。

目前如果我curl -X GET localhost:3000/test/Owen它会抛出一个类型错误,因为它不在数据库中。

如果给出上述代码和示例,如何捕获错误?

2 个答案:

答案 0 :(得分:2)

首先,我认为你应该使用next()发回你在回调中收到的错误:

app.get( "/test/:lastName", function ( req, resp, next ) {
  // some code...
    if ( err ) {
      return next("1 mess " + err)
    }

关于TypeError,它正在发生,因为当没有任何结果时你从MongoDB获得undefined,但这不是错误,所以它不会进入if。在这些情况下,您应该检查对象是否存在,例如:

resp.json( res && res.rate || {} )

Here您还有另一个关于如何在这些情况下处理错误的示例:

app.param('user', function(req, res, next, id) {

  // try to get the user details from the User model and attach it to the request object
  User.find(id, function(err, user) {
    if (err) {
      next(err);
    } else if (user) {
      req.user = user;
      next();
    } else {
      next(new Error('failed to load user'));
    }
  });
});

答案 1 :(得分:1)

如果找不到请求的查询,MongoDB将返回一个空对象。所以你需要考虑如何处理这些回应,正如Antonio Val在他的回答中所说的那样。

但是,错误的处理方式与使用next()不同,例如将resp传递给函数以处理使用错误对象或其他自定义消息调用resp.json()的错误并添加statusCode,以便端点的被调用者也可以处理错误。

例如,无论你怎么称呼它都会改变:

if ( err ) {
    console.error("1 mess " + err)
}

对此:

if ( err ) {
    console.error("1 mess " + err)
    handleErrors(resp, err)
}

然后创建函数handleErrors()

function handleErrors(resp, err) {
    // its up to you how you might parse the types of errors and give them codes,
    // you can do that inside the function 
    // or even pass a code to the function based on where it is called.

    resp.statusCode = 503;
    const error = new Error(err);
    resp.send({error})
}