express-exception-handler
Advanced tools
Comparing version 0.0.3 to 0.0.4
class ExceptionCustom extends Error { | ||
constructor (message, status) { | ||
constructor (message, status, response) { | ||
super(message || 'Unknown Exception') | ||
@@ -7,2 +7,3 @@ Error.captureStackTrace(this, this.constructor) | ||
this.status = status || 500 | ||
this.response = response | ||
} | ||
@@ -9,0 +10,0 @@ } |
function exceptionMiddleware (err, req, res, next) { | ||
res.sendStatus(err.status) | ||
res.status(err.status).send(err.response || err.message); | ||
} | ||
module.exports = exceptionMiddleware |
{ | ||
"name": "express-exception-handler", | ||
"version": "0.0.3", | ||
"version": "0.0.4", | ||
"description": "a top level exception handle package", | ||
@@ -5,0 +5,0 @@ "main": "lib/index.js", |
@@ -33,3 +33,3 @@ #  | ||
router.post('/', async (req, res) => { | ||
throw new HttpError('Great Message', 400) | ||
throw new HttpError('Great Message', 400, "{Response: awesome}") | ||
})) | ||
@@ -36,0 +36,0 @@ ``` |
@@ -19,2 +19,17 @@ var exception = require('../lib/custom-exception') | ||
}) | ||
test(' exceptios has undefined response', async () => { | ||
var ex = new exception() | ||
expect(ex.response).toBeUndefined() | ||
}) | ||
test('exceptios set parameter', async () => { | ||
var response = "a response" | ||
var status = 400 | ||
var message = "some message" | ||
var ex = new exception(message, status, response) | ||
expect(ex.status).toBe(status) | ||
expect(ex.response).toBe(response) | ||
expect(ex.message).toBe(message) | ||
}) | ||
}) |
const middleware = require('../lib/middleware') | ||
describe('test the middleware', () => { | ||
test('exception middleware sends error status', () => { | ||
test('exception middleware sends error status without response', () => { | ||
var res = { | ||
sendStatus: jest.fn() | ||
status: jest.fn(() => res), | ||
send: jest.fn(() => res) | ||
} | ||
middleware({status:500}, undefined,res) | ||
expect(res.sendStatus.mock.calls.length).toBe(1) | ||
expect(res.sendStatus.mock.calls[0][0]).toBe(500) | ||
middleware({status:500, message: "some message"}, undefined,res) | ||
expect(res.status.mock.calls.length).toBe(1) | ||
expect(res.status.mock.calls[0][0]).toBe(500) | ||
expect(res.send.mock.calls.length).toBe(1) | ||
expect(res.send.mock.calls[0][0]).toBe("some message") | ||
}) | ||
test('exception middleware sends error status with response', () => { | ||
var res = { | ||
status: jest.fn(() => res), | ||
send: jest.fn(() => res) | ||
} | ||
middleware({status:400, message: "some message", response: "a response"}, undefined,res) | ||
expect(res.status.mock.calls.length).toBe(1) | ||
expect(res.status.mock.calls[0][0]).toBe(400) | ||
expect(res.send.mock.calls.length).toBe(1) | ||
expect(res.send.mock.calls[0][0]).toBe("a response") | ||
expect(res.send.mock.calls[0][0]).not.toBe("some message") | ||
}) | ||
}) |
78858
143