From a14dc0addff80c1886a04f1f8daa6506dfb8d215 Mon Sep 17 00:00:00 2001 From: Marcin Rataj Date: Fri, 8 Nov 2019 16:37:27 +0100 Subject: [PATCH] Add section on "Error Codes" to CONTRIBUTING_JS.md (#445) * Update CONTRIBUTING_JS.md add section on error codes Ref. https://github.com/ipfs/js-ipfs/pull/2547#discussion_r336466026 * Update CONTRIBUTING_JS.md Co-Authored-By: Teri Chadbourne * docs: add Error Codes example License: MIT Signed-off-by: Marcin Rataj * Update CONTRIBUTING_JS.md Co-Authored-By: Teri Chadbourne --- CONTRIBUTING_JS.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) 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.