Express.js和gridfs-stream无法捕获错误
这是一个简单的图像(图片)下载服务器,Express.js接收请求,从MongoDB GridFS获取图像,并用该文件进行响应。
当请求有效时(当请求的文件存在时)可以。
问题是,当查询失败时,我无法捕捉到MongoError
(即请求的图像不存在)。
import Grid from 'gridfs-stream' const root = 'fs_images' // This func returns the file stream export function getReadStream (id) { const gfs = Grid(mongoose.connection.db, mongoose.mongo) const options = { _id: id, mode: 'r', root: root } const readStream = gfs.createReadStream(options) readStream.on('error', function (err) { // throw here // it performs the same without this on-error hook; // if comment the `throw err`, nothing will happens // but I want the caller knows the error throw err }) return readStream }
这是路由器
router.get('/:fileId', function (req, res, next) { const fileId = req.params.fileId try { const imgReadStream = image.getReadStream(fileId) imgReadStream.pipe(res) } catch (err) { // nothing catched here // instead, the process just crashed console.log(err) } }
我不能抓住这个错误。 当我尝试请求不存在的东西时, MongoError
在控制台中显示,并且应用程序与errno
崩溃为1
。
控制台输出端:
/.../node_modules/mongodb/lib/utils.js:123 process.nextTick(function() { throw err; }); ^ MongoError: file with id 123456123456123456123456 not opened for writing at Function.MongoError.create (/.../node_modules/mongodb-core/lib/error.js:31:11)
这可能有点不同。 如果在其他地方抛出一个Error
它会被我的error handling程序( app.use(function(err, req, res, next){ /* ... */})
)捕获,或者至less由Express.js
,并返回一个500
,没有进程崩溃。
总之,我希望应用程序知道并捕获这个MongoError
所以我可以手动处理它(即返回一个404
响应)。
try
/ catch
将无法正常工作,因为错误发生在不同的滴答(asynchronous)。 也许你可以听取路由器中的错误呢?
const imgReadStream = image.getReadStream(fileId) imgReadStream.on('error', function(err) { // Handle error }); imgReadStream.pipe(res)