Error handling: on non-error throw try to stringify if error is an object (#1113)

This commit is contained in:
Alexsey 2017-12-24 14:48:44 +02:00 committed by Yiyu He
parent 53bea20e79
commit 6baa41178d
2 changed files with 20 additions and 1 deletions

View file

@ -5,6 +5,7 @@
* Module dependencies.
*/
const util = require('util');
const createError = require('http-errors');
const httpAssert = require('http-assert');
const delegate = require('delegates');
@ -105,7 +106,7 @@ const proto = module.exports = {
// to node-style callbacks.
if (null == err) return;
if (!(err instanceof Error)) err = new Error(`non-error thrown: ${err}`);
if (!(err instanceof Error)) err = new Error(util.format('non-error thrown: %j', err));
let headerSent = false;
if (this.headerSent || !this.writable) {

View file

@ -185,5 +185,23 @@ describe('ctx.onerror(err)', () => {
assert.equal(removed, 2);
});
it('should stringify error if it is an object', done => {
const app = new Koa();
app.on('error', err => {
assert.equal(err, 'Error: non-error thrown: {"key":"value"}');
done();
});
app.use(async ctx => {
throw {key: 'value'}; // eslint-disable-line no-throw-literal
});
request(app.callback())
.get('/')
.expect(500)
.expect('Internal Server Error', () => {});
});
});
});