diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6ddcf18..6a6f048 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,7 +12,7 @@ jobs: strategy: matrix: - node: ['10', '12', '14', '15'] + node: ['10', '12', '14', '16', '18'] name: Node ${{ matrix.node }} testing diff --git a/demos/error/index.js b/demos/error/index.js index 3c0d78d..ead1505 100644 --- a/demos/error/index.js +++ b/demos/error/index.js @@ -26,4 +26,4 @@ app.use((error, req, res, next) => { res.send('test.', 500); }); -app.listen(4000, () => console.log('Server is listening on port 3000...')); +app.listen(3000, () => console.log('Server is listening on port 3000...')); diff --git a/lib/router.js b/lib/router.js index 0fa1b8c..1b1c56d 100644 --- a/lib/router.js +++ b/lib/router.js @@ -106,9 +106,12 @@ class Router { const router = routers[i]; for (let j = 0; j < router.routes.length; j += 1) { - const { path: childPath, middlewarePath, fns, method } = router.routes[ - j - ]; + const { + path: childPath, + middlewarePath, + fns, + method, + } = router.routes[j]; const path = (route + (childPath || middlewarePath || '')).replace( /\/{1,}/g, @@ -210,6 +213,11 @@ class Router { if (typeof fn === 'function' && fn.length === 4) return fn(error, req, res, next); + const nextFn = handlers[id]; + if (typeof nextFn === 'function' && nextFn.length === 4) { + return nextFn(error, req, res, next); + } + return res.send(error.stack, error.status || 500); } diff --git a/tests/error-handling/custom.js b/tests/error-handling/custom.js new file mode 100644 index 0000000..f8cd0c2 --- /dev/null +++ b/tests/error-handling/custom.js @@ -0,0 +1,23 @@ +const pureHttp = require('../..'); + +module.exports = function () { + const app = pureHttp(); + + app.get( + '/custom', + (_req, _res, _next) => { + throw new Error('bad'); + }, + /* istanbul ignore next */ + // ignore coverage for this function because it will never be called. + (req, res, _next) => { + res.send('good'); + }, + ); + + app.use((error, req, res, _next) => { + res.send('Something went wrong.', 500); + }); + + return app; +}; diff --git a/tests/error-handling/custom.test.js b/tests/error-handling/custom.test.js new file mode 100644 index 0000000..8f7f709 --- /dev/null +++ b/tests/error-handling/custom.test.js @@ -0,0 +1,16 @@ +/* eslint-disable global-require */ +/* eslint-disable no-unused-vars */ +const supertest = require('supertest'); + +describe('ALL /not-found', () => { + it(`The status should be 404.`, async () => { + const app = require('./custom')(); + + const request = supertest(app); + + const res = await request.get('/custom'); + + expect(res.statusCode).toBe(500); + expect(res.text).toBe('Something went wrong.'); + }); +});