Skip to content

Commit

Permalink
Error handling: on non-error throw try to stringify if error is an ob…
Browse files Browse the repository at this point in the history
…ject (#1113)
  • Loading branch information
Alexsey authored and dead-horse committed Dec 24, 2017
1 parent 53bea20 commit 6baa411
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/context.js
Expand Up @@ -5,6 +5,7 @@
* Module dependencies.
*/

const util = require('util');
const createError = require('http-errors');
const httpAssert = require('http-assert');
const delegate = require('delegates');
Expand Down Expand Up @@ -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) {
Expand Down
18 changes: 18 additions & 0 deletions test/context/onerror.js
Expand Up @@ -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', () => {});
});
});
});

0 comments on commit 6baa411

Please sign in to comment.