2017-10-19 24 views
1

這是一個簡單的圖片(圖片)下載服務器,Express.js接收請求,從MongoDB GridFS獲取圖像,並用該文件進行響應。無法使用Express.js和gridfs-stream捕獲錯誤

當請求有效時(當請求的文件存在時)可以。

問題是,當查詢失敗時(即所請求的圖像不存在),我無法捕捉到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顯示,並且應用程序崩潰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) 

這可能是有點不同。如果其他地方拋出Error,它將被我的錯誤處理程序(app.use(function(err, req, res, next){ /* ... */}))或至少由Express.js的默認處理程序捕獲,並返回500,而不會導致進程崩潰。

簡而言之,我希望應用程序知道並捕獲此MongoError,以便我可以手動處理它(即返回404響應)。

回答

1

try/catch將不起作用,因爲錯誤發生在不同的滴答(異步)。也許你可以聽取路由器中的錯誤?

const imgReadStream = image.getReadStream(fileId) 

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

imgReadStream.pipe(res) 
相關問題