处理嵌套promise所引发的异常

时间:2017-06-24 00:54:07

标签: javascript node.js bluebird

我不明白为什么我的应用程序会抛出未处理的异常,或者我如何避免这种情况。 reject(new Error('...'))

会抛出异常

抛出异常的函数:

function parseSourceStrings(fileInformation, callback) {
    var filePath = fileInformation.path
    var fileExtension = path.extname(filePath)
    switch(fileExtension) {
        case '.pot':
        case '.po':
            return new Promise(function(resolve, reject) {
                poProcessor.processFile(filePath).then(function(result) {
                    result = addMetaData(fileInformation, result)
                    resolve(result)
                }).catch(function(err) {
                    reject(err)
                })
            })
        default:
            return new Promise(function(resolve, reject) {
                reject(new Error('Unknwown file format'))
            })
    }
}

这就是我调用函数的方式:

mv(filePath, targetFilePath, {mkdirp: true}).then(function() {
    return uploadHandler.parseSourceStrings(fileInformation)
}).then(function(parsedSourceStrings) {
    console.log(parsedSourceStrings)
}).catch(function(err) {
    logger.error(err)
    next(err)
})

引发的异常:

2:50:19 AM - error: Error: Unknwown file format
    at result.meta_information (c:\Users\h9pe\Documents\tms-reworked\app\projects\process-uploads\upload-handler.js:34:12)
    at Object.parseSourceStrings (c:\Users\h9pe\Documents\tms-reworked\app\projects\process-uploads\upload-handler.js:33:11)
    at c:\Users\h9pe\Documents\tms-reworked\app\projects\router.js:117:26
    at tryCatcher (c:\Users\h9pe\Documents\tms-reworked\node_modules\bluebird\js\release\util.js:16:23)
    at Promise.module.exports.Promise._settlePromiseFromHandler (c:\Users\h9pe\Documents\tms-reworked\node_modules\bluebird\js\release\promise.js:512:31)
    at Promise.module.exports.Promise._settlePromise (c:\Users\h9pe\Documents\tms-reworked\node_modules\bluebird\js\release\promise.js:569:18)
    at Promise.module.exports.Promise._settlePromise0 (c:\Users\h9pe\Documents\tms-reworked\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise.module.exports.Promise._settlePromises (c:\Users\h9pe\Documents\tms-reworked\node_modules\bluebird\js\release\promise.js:693:18)
    at Promise.module.exports.Promise._fulfill (c:\Users\h9pe\Documents\tms-reworked\node_modules\bluebird\js\release\promise.js:638:18)
    at module.exports (c:\Users\h9pe\Documents\tms-reworked\node_modules\bluebird\js\release\nodeback.js:42:21)
    at c:\Users\h9pe\Documents\tms-reworked\node_modules\mv\index.js:34:26
    at FSReqWrap.oncomplete (fs.js:123:15) '/projects/13/update/sourcestrings'

显然它只是一个未处理的异常,但抓住了应该抓住抛出的异常没有?我如何正确捕捉异常?

0 个答案:

没有答案