Skip to content

Commit

Permalink
feat: stringify err object on non-error (#36)
Browse files Browse the repository at this point in the history
The `err` may be an object and the error message would print as `nodejs.Error: non-error thrown: [object Object]` which is not helpful, try to stringify it.
  • Loading branch information
dickeylth authored Feb 9, 2022
1 parent 9fdb665 commit 9a899f5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,14 @@ module.exports = function onerror(app, options) {

// wrap non-error object
if (!(err instanceof Error)) {
const newError = new Error('non-error thrown: ' + err);
let errMsg = err;
if (typeof err === 'object') {
try {
errMsg = JSON.stringify(err);
// eslint-disable-next-line no-empty
} catch (e) {}
}
const newError = new Error('non-error thrown: ' + errMsg);
// err maybe an object, try to copy the name, message and stack to the new error instance
if (err) {
if (err.name) newError.name = err.name;
Expand Down
17 changes: 16 additions & 1 deletion test/json.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ describe('json.test.js', () => {
.expect({ error: 'Internal Server Error' }, done);
});

it('should wrap non-error object', done => {
it('should wrap non-error primitive value', done => {
const app = new koa();
app.on('error', () => {});
onerror(app);
Expand All @@ -86,6 +86,21 @@ describe('json.test.js', () => {
.expect({ error: 'non-error thrown: 1' }, done);
});

it('should wrap non-error object and stringify it', done => {
const app = new koa();
app.on('error', () => {});
onerror(app);
app.use(() => {
throw { error: true };
});

request(app.callback())
.get('/')
.set('Accept', 'application/json')
.expect(500)
.expect({ error: 'non-error thrown: {"error":true}' }, done);
});

it('should wrap mock error obj instead of Error instance', done => {
done = pedding(2, done);
const app = new koa();
Expand Down

0 comments on commit 9a899f5

Please sign in to comment.