Skip to content
This repository has been archived by the owner on Nov 9, 2023. It is now read-only.

Commit

Permalink
call next returnHandler even if errors occurred
Browse files Browse the repository at this point in the history
  • Loading branch information
kumavis committed Dec 10, 2018
1 parent fb19386 commit 6de511a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 5 deletions.
28 changes: 23 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ class RpcEngine extends SafeEventEmitter {
}
// process all middleware
this._runMiddleware(req, res, (err) => {
// take a clear any responseError
const responseError = res._originalError
delete res._originalError
if (responseError) {
// ensure no result is present on an errored response
delete res.result
// return originalError and response
return cb(responseError, res)
}
// return response
cb(err, res)
})
Expand Down Expand Up @@ -96,7 +105,11 @@ class RpcEngine extends SafeEventEmitter {
cb()
}
function end (err) {
if (err) return cb(err)
// if errored, set the error but dont pass to callback
if (err) {
res.error = serializeError(err)
res._originalError = err
}
// mark as completed
isComplete = true
cb()
Expand All @@ -105,12 +118,10 @@ class RpcEngine extends SafeEventEmitter {

// returns, indicating whether or not it ended
function completeRequest (err) {
// this is an internal catastrophic error, not an error from middleware
if (err) {
// prepare error message
res.error = {
code: err.code || -32603,
message: err.stack,
}
res.error = serializeError(err)
// return error-first and res with err
return onDone(err, res)
}
Expand All @@ -125,4 +136,11 @@ class RpcEngine extends SafeEventEmitter {
}
}

function serializeError(err) {
return {
code: err.code || -32603,
message: err.stack,
}
}

module.exports = RpcEngine
26 changes: 26 additions & 0 deletions test/basic.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,4 +210,30 @@ describe('basic tests', function () {
done()
})
})

it('calls back next handler even if error', function (done) {
let engine = new RpcEngine()

let sawNextReturnHandlerCalled = false

engine.push(function (req, res, next, end) {
next(function (cb) {
sawNextReturnHandlerCalled = true
cb()
})
})

engine.push(function(req, res, next, end) {
end(new Error('boom'))
})

let payload = { id: 1, jsonrpc: '2.0', method: 'hello' }

engine.handle(payload, (err, res) => {
assert(err, 'did error')
assert(sawNextReturnHandlerCalled, 'saw next return handler called')
done()
})
})

})

0 comments on commit 6de511a

Please sign in to comment.