Allow ability to log middleware errors (#95)

This commit is contained in:
David Luecke 2017-11-19 12:34:35 -08:00
parent 108469a27d
commit 4b5c62d962
2 changed files with 23 additions and 3 deletions

View File

@ -2,7 +2,8 @@ const path = require('path');
const errors = require('./index');
const defaults = {
public: path.resolve(__dirname, 'public')
public: path.resolve(__dirname, 'public'),
logger: console
};
const defaultHtmlError = path.resolve(defaults.public, 'default.html');
@ -22,6 +23,11 @@ module.exports = function (options = {}) {
}
return function (error, req, res, next) {
// Log the error if it didn't come from a service method call
if (options.logger && typeof options.logger.error === 'function' && !res.hook) {
options.logger.error(error);
}
if (error.type !== 'FeathersError') {
let oldError = error;
error = new errors.GeneralError(oldError.message, {
@ -91,7 +97,7 @@ module.exports = function (options = {}) {
if (contentType.indexOf('json') !== -1 || accepts.indexOf('json') !== -1) {
formatter['application/json'](error, req, res, next);
} else if (options.html && (contentType.indexOf('html') !== -1 || accepts.indexOf('html') !== -1)) {
return formatter['text/html'](error, req, res, next);
formatter['text/html'](error, req, res, next);
} else {
// TODO (EK): Maybe just return plain text
formatter['application/json'](error, req, res, next);

View File

@ -39,6 +39,8 @@ describe('error-handler', () => {
});
describe('supports catch-all custom handlers', function () {
let currentError;
before(function () {
this.app = feathers()
.get('/error', function (req, res, next) {
@ -46,7 +48,12 @@ describe('error-handler', () => {
})
.use(handler({
html: htmlHandler,
json: jsonHandler
json: jsonHandler,
logger: {
error (e) {
currentError = e;
}
}
}));
this.server = this.app.listen(5050);
@ -72,6 +79,13 @@ describe('error-handler', () => {
});
});
it('logs the error', done => {
request(options, (error, res, body) => {
expect(currentError.message).to.equal('Something went wrong');
done();
});
});
it('can send a custom response', done => {
request(options, (error, res, body) => {
expect(body).to.equal(content);