diff --git a/CONTRIBUTING_JS.md b/CONTRIBUTING_JS.md index 63d96e0d..c7ff617f 100644 --- a/CONTRIBUTING_JS.md +++ b/CONTRIBUTING_JS.md @@ -19,6 +19,7 @@ Our toolkit for each of these is not set in stone, and we don't plan to halt our - [Guidelines](#guidelines) - [Supported versions](#supported-versions) - [Linting & Code Style](#linting--code-style) + - [Error Codes](#error-codes) - [Dependency Versions](#dependency-versions) - [Testing](#testing) - [Releasing](#releasing) @@ -100,6 +101,41 @@ However, we've added an extra linting rule: Enforce the use of [strict mode](htt Using [aegir-lint](#aegir) will help you do this easily; it automatically lints your code. +#### Error Codes + +When introducing a new error code that may be useful outside of the current scope, make sure it is exported as a new `Error` type: + +```js +class NotFoundError extends Error { + constructor (message) { + super(message || 'Resource was not found') + this.name = 'NotFoundError' + this.code = NotFoundError.code + } +} + +NotFoundError.code = 'ERR_NOT_FOUND' +exports.NotFoundError = NotFoundError +``` + + +This enables others to reuse those definitions and decreases the number of hardcoded values across our codebases. +For example: + +```js +const { NotFoundError } = require('some-module') + +// throw predefined errors types +if (!value) { + throw new NotFoundError() +} + +// compare against code from imported type +if (err.code === NotFoundError.code) { + // handle +} +``` + #### Dependency Versions Our rule is: Use ~ for everything below 1.0.0 and ^ for everything above 1.0.0. If you find a package.json that is not following this rule, please submit a PR.