Javascript Node/Express Rest API-如何从mssql引发错误

Javascript Node/Express Rest API-如何从mssql引发错误,javascript,sql-server,node.js,rest,express,Javascript,Sql Server,Node.js,Rest,Express,我对javascript和Node/Express都很陌生,这可能是一个新手问题,但接下来 我正在构建一个Rest API,并希望从此函数中抛出新错误(err.message): function hentForfatter(id, callback) { sql.connect(config, function(err) { if(err) { console.log(err); callback(err);

我对javascript和Node/Express都很陌生,这可能是一个新手问题,但接下来

我正在构建一个Rest API,并希望
从此函数中抛出新错误(err.message)

function hentForfatter(id, callback) {

        sql.connect(config, function(err) {

        if(err) {
            console.log(err);
            callback(err);
        }

        new sql.Request().query('SELECT * from Forfatter where ForfatterID = ' + id).then(function(recordset) {
            callback(recordset[0]);
        })

        .catch(function(err) {
            console.log(err);
            callback(err);
        });

    });
}
。。。因此,我可以在Express API路线中执行此操作:

router.get('/:forfatterid/quizer/:quiz_id', function(req, res, next) {

    try {
        db.hentQuiz(1, function(result) {
            res.setHeader('Content-Type', 'application/json');
            res.send(JSON.stringify(result));
        });
    } 

    catch (error) {
        res.status(404).send(error)
    }

});

我不知道该怎么做。。。有人能帮忙吗?:)

如果使用回调,请尝试使用两个参数:

callback(err, result)
然后检查
错误
结果


此外,请查看承诺链的工作原理。

如果使用回调,请尝试使用两个参数:

callback(err, result)
然后检查
错误
结果


此外,还可以查看承诺链是如何工作的。

在node中,有一个约定,回调的第一个参数应该是潜在的错误

function hentForfatter(id, callback) {

  sql.connect(config, function(err) {

    if(err) {
        console.log(err);
        return callback(err); //notice the return statement
    }

    new sql.Request().query('SELECT * from Forfatter where ForfatterID = ' + id).then(function(recordset) {
        callback(null, recordset[0]); //notice I send null for the error
    })

    .catch(function(err) {
        console.log(err);
        callback(err);
    });

  });
}
(我不知道如何从
db.hentQuiz
hentForfatter


在节点中,有一个约定,回调的第一个参数应该是潜在错误

function hentForfatter(id, callback) {

  sql.connect(config, function(err) {

    if(err) {
        console.log(err);
        return callback(err); //notice the return statement
    }

    new sql.Request().query('SELECT * from Forfatter where ForfatterID = ' + id).then(function(recordset) {
        callback(null, recordset[0]); //notice I send null for the error
    })

    .catch(function(err) {
        console.log(err);
        callback(err);
    });

  });
}
(我不知道如何从
db.hentQuiz
hentForfatter


请看是否有用?请让我们知道您使用的是什么库。请看是否有用?请让我们知道您使用的是什么库。tooThanks,似乎我将使用error作为回调参数而不是try/catch模式来寻找您的解决方案。我只是想找出在这种情况下处理错误的“正确”方法。谢谢,看来我会选择使用error作为回调参数而不是try/catch模式的解决方案。只是想找出在这种情况下进行错误处理的“正确”方法。