restify/errors

Custom error toString()

Closed this issue · 0 comments

Custom errors created via makeConstructor() return the generic constructor name (ErrCtor) when applying toString():

> const errors = require('restify-errors');

> errors.makeConstructor('CustomError', { statusCode: 400 });
> const cerr = new errors.CustomError('oops');
> cerr.toString();
'ErrCtor: oops'
// Expected: 'CustomError: oops'

toJSON() serialization is also affected for MultiErrors if the "cause" is a custom error:

> const merr = new errors.BadGatewayError(cerr, {message: 'Unable...'});

> merr.toString();
'BadGatewayError: Unable...; caused by ErrCtor: oops'

> merr.toJSON();
{ code: 'BadGateway',
  message: 'Unable...; caused by ErrCtor: oops' }

This can be traced to VError.toString(), which checks the instance for its own name property, and navigates up the prototype chain to land on the constructor name. For custom error instances, cerr.hasOwnProperty('name') === false, yielding ErrCtor.

Options:

  1. Users can provide a custom toString() implementation if this is important to them
  2. set this.name = name in the constructor: https://github.com/restify/errors/blob/master/lib/index.js#L75