Skip to content

Custom error toString() #74

@ltvolks

Description

@ltvolks

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions