gpt4 book ai didi

express - 快速异步/等待错误处理

转载 作者:行者123 更新时间:2023-12-03 07:58:16 25 4
gpt4 key购买 nike

class XYZ {

constructor(app) {

// app is express object
this.app = app;

this.app.route('/api/url')
.get(this.wrap(this.urlhandler.bind(this)));

// to send error as json -> this never gets invoked ??
this.app.use((err, req, res, next) => {
res.status(400).json({error: err});
next(err);
});

}

// wraps each async route function to handle rejection and throw errors
wrap(fn) {
return function (req, res, next) {
Promise.resolve(fn(req, res, next)).catch(function (err) {
console.log('ERROR OCCURED: > > > > > > > ', err.code);
next(err)
});
}
}

}

每个快速ASYNC路由都经过包装,以捕获路由处理程序函数中的任何拒绝或抛出错误。每当出现这样的拒绝或错误时,wrap都会被调用,并且我能够看到“ERROR OCCURED>>> ..”的打印。

但是,我无法将该错误传递给错误处理程序中间件,在该处我打算将​​JSON错误发送给400。

如何在上述情况下解决此问题?

最佳答案

抱歉,我无法隔离示例代码来轻松演示该错误。我正在使用mysql Express-与promise和ES6混合使用。

以下是我遇到的一个问题样本及其解决方案。

问题:我在初始化路由之前添加了错误处理中间件。最后添加错误中间件即可解决!!! (Thanks to this stackoverflow question)。

var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser')
var morgan = require('morgan');

//define class
class Sql {

constructor(pool) {
this.pool = pool;
}

exec(query, params) {
let _this = this;
return new Promise(function (resolve, reject) {
_this.pool.query(query, params, function (error, rows, _fields) {
if (error) {
return reject(error);
}
return resolve(rows);
});
});
}

}


//define class
class Api {

constructor(mysqlPool, app) {
this.mysql = new Sql(mysqlPool)
this.app = app;

// this.app.use(this.errMw)
//console.log('IF ERROR MIDDLEWARE IS ADDED HERE - it was NEVER CALLED');

/**************** add middleware and routes ****************/
this.app.get('/', this.asyncWrap(this.root.bind(this)))
this.app.use(this.errMw) // << USE ERROR MIDDLEWARE HERE
}

errMw(err, req, res, next) {

res.status(400).json({error: err});
next(err);
}

asyncWrap(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch((err) => {
console.log('err > > > > >', err.message);
next(err);
});
}
}


run(cbk) {
this.app.listen(3000)
}

async root(req, res) {
res.json(await this.mysql.exec('select * from customer', []))
}

}


/**************** START : mysql,express,api -> run ****************/

let args = {}
args['host'] = 'localhost'
args['user'] = 'root'
args['password'] = 'secret'
args['database'] = 'models'

let mysqlPool = mysql.createPool(args)
let app = express()
//app.use(morgan('tiny'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))


let api = new Api(mysqlPool, app);
api.run()


/**************** END : mysql,express,api -> run ****************/

关于express - 快速异步/等待错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46929330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com