Skip to content

Commit f5368f8

Browse files
committed
Correctly chain finally on on-error
1 parent 03c55a4 commit f5368f8

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
lines changed

src/utils/run-handler-with-middleware.js

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,11 @@ export default function runHandlerWithMiddleware (fn, cb, responseObject, regist
4141
const runPostExecute = processPluginsForEvent(PluginHook.POST_EXECUTE)
4242
const runError = processPluginsForEvent(PluginHook.ON_ERROR)
4343
const runFinally = () => {
44-
processPluginsForEvent(PluginHook.FINALLY)
45-
delete global.CONTEXT
44+
return processPluginsForEvent(PluginHook.FINALLY)()
45+
.then(res => {
46+
delete global.CONTEXT
47+
return res
48+
})
4649
}
4750

4851
// Execute the middleware stack using the above request and response
@@ -57,13 +60,15 @@ export default function runHandlerWithMiddleware (fn, cb, responseObject, regist
5760
// Execute the callback
5861
.then(
5962
() => {
60-
runFinally()
61-
cb(null, responseObject, callback)
63+
return Promise.resolve()
64+
.then(() => runFinally())
65+
.then(() => cb(null, responseObject, callback))
6266
},
6367
err => {
64-
runError(err)
65-
runFinally()
66-
cb(err, responseObject, callback)
68+
return Promise.resolve()
69+
.then(() => runError(err))
70+
.then(() => runFinally())
71+
.then(() => cb(err, responseObject, callback))
6772
}
6873
)
6974
}

test/unit/utils/compose-middleware.spec.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,5 +42,23 @@ describe('compose middleware', () => {
4242
executionCount.should.equal(2)
4343
})
4444
})
45+
46+
it('should reject the promise if middleware throws an error', () => {
47+
const middlewareA = (req, res, done) => {
48+
req.should.equal('hello')
49+
res.should.equal('world')
50+
throw new Error('test-error')
51+
}
52+
53+
const middleware = [ middlewareA ]
54+
55+
return composeMiddleware(middleware)('hello', 'world')
56+
.then(() => {
57+
throw new Error('Test expected to fail')
58+
})
59+
.catch(err => {
60+
err.message.should.equal('test-error')
61+
})
62+
})
4563
})
4664
})

0 commit comments

Comments
 (0)