Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

node express 异步错误处理?

dao 层 daoUser.js

/**
 *  用户注册
 * @param params
 * @param callback
 */
exports.insert = function (params, callback) {
    let post = Object.assign(params, {date: new Date()});
    pool.query('INSERT INTO user SET ?', post, function (error, results, fields) {
        if (error) throw error;
        for (let key in error) {
            console.log(key + "==" + error[key]);
        }
        console.log(results);
        console.log("============sql===========");
        console.log(fields);
        callback(JSON.parse(JSON.stringify(results)));
    });
}

重复注册导致的唯一约束报错,关键是怎么在外层app.js中去捕获处理。不想所有异步可能出错的地方都加try{}catch 处理

或者从路由层到service层到数据dao层依次把route层的next传递下去?

app.js

//错误处理
app.use(function(err, req, res, next) {
    console.log("=================错误处理=================")
    //其他 业务逻辑

    if (res.headersSent) {
        return next(err);
    }
    res.status(500);
    res.render('error', { error: err });
});

这里并没有捕获数据库操作的异常


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

insert函数模拟异步回调写法,让外层去判断声明函数返回的第一个参数是error还是null。

const insert = (data, cb) => {
    data...
    if(error){
        cb(error);
    }else{
        cb(null, data);
    }
}

对应实例

exports.insert = function (params, callback) {
    let post = Object.assign(params, {date: new Date()});
    pool.query('INSERT INTO user SET ?', post, function (error, results, fields) {
        // 下面改了
        if (error) {
            callback(error);
        for (let key in error) {
            console.log(key + "==" + error[key]);
        }
        console.log(results);
        console.log("============sql===========");
        console.log(fields);
        // 下面改了
        callback(null, JSON.parse(JSON.stringify(results)));
    });
}

外层 express 有(req, res, next) => {}函数,让next()接收insert()函数的返回值,错误最终会传递给APP.js的错误处理中间件,成功执行会跳过。

soonfy


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...