2017-10-19 8 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이 콘솔에 표시되고 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을 던지면 내 오류 처리기 (app.use(function(err, req, res, next){ /* ... */})) 또는 적어도 Express.js의 기본 처리기로 캐치되며 처리가 중지되지 않고 500을 반환합니다.

간단히 말해서 앱에이 사실을 알고 붙잡아서 수동으로 처리 할 수 ​​있도록 (404 응답) MongoError입니다.

답변

1

try/catch 오류가 다른 틱 (비동기식)으로 발생하기 때문에 작동하지 않습니다. 아마도 라우터의 오류를 대신들을 수 있습니까?

const imgReadStream = image.getReadStream(fileId) 

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

imgReadStream.pipe(res)