1

它是一个简单的图像(图片)下载服务器,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)
    }
}

我就是抓不住错误。当我尝试请求一些不存在的东西时,控制台中的节目会显示出来,并且应用程序会因isMongoError崩溃。errno1

控制台输出负责人:

/.../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)

这可能有点不同。如果其他地方抛出 an Error,它将被我的错误处理程序 ( app.use(function(err, req, res, next){ /* ... */})) 捕获,或者至少被来自 的默认处理程序捕获Express.js,并返回 a 500,而不会导致进程崩溃。

简而言之,我希望应用程序知道并捕捉到这一点MongoError,以便我可以手动处理它(即返回404响应)。

4

1 回答 1

1

try/catch将不起作用,因为错误发生在不同的滴答声中(异步)。也许您可以改为监听路由器中的错误?

const imgReadStream = image.getReadStream(fileId)

imgReadStream.on('error', function(err) {
    // Handle error
});

imgReadStream.pipe(res)
于 2017-10-19T06:18:13.660 回答