Skip to content

Should Node.js standard library throw custom Error subclasses? #8342

Closed
@Ginden

Description

@Ginden

As we know, ECMAScript define only few Error subclasses. W3C specifications adds to this list DOMException and URIError. Right now, Node.js implements seven Errors:

  • Error
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

On other side we have Java standard library that defines 74 classes extending java.lang.Exception and numerous other extending these subclasses. Most of them doesn't make sense in Node.js context, as our standard library is much smaller, but I'm convinced that 7 errors defined in ECMAScript are too general to provide meaningful information on types of error that can happen.

Therefore, I propose:

  • make all exceptions coming from syscalls inherit from new class SystemError (class SystemError extends Error)
    • create classes like FileSystemError and NetworkError to inherit from SystemError
  • add class DeprecationError inheriting from Errror for deprecated features
  • discourage creating direct instances of Error in standard library

Disadvantages:

  • code directly checking err.constructor === TypeError can break

Advantages:

  • better typing for TypeScript
    • many IDEs can use TypeScript definition files and use them as ad-hoc documentation, even if you write in JavaScript
  • Bluebird .catch(klass, handler) easier to use

Loose ideas:

  • export classes like DatabaseError to be subclassed by database modules

I'm working on pull request to replace new Error with new TypeError or new RangeError wherever it makes sense.

Metadata

Metadata

Assignees

No one assigned

    Labels

    errorsIssues and PRs related to JavaScript errors originated in Node.js core.feature requestIssues that request new features to be added to Node.js.stale

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions