Skip to content

Commit a14dc0a

Browse files
lidelterichadbourne
authored and
Alan Shaw
committed
Add section on "Error Codes" to CONTRIBUTING_JS.md (#445)
* Update CONTRIBUTING_JS.md add section on error codes Ref. ipfs/js-ipfs#2547 (comment) * Update CONTRIBUTING_JS.md Co-Authored-By: Teri Chadbourne <terichadbourne@users.noreply.github.com> * docs: add Error Codes example License: MIT Signed-off-by: Marcin Rataj <lidel@lidel.org> * Update CONTRIBUTING_JS.md Co-Authored-By: Teri Chadbourne <terichadbourne@users.noreply.github.com>
1 parent 051f97c commit a14dc0a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Diff for: CONTRIBUTING_JS.md

+36
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Our toolkit for each of these is not set in stone, and we don't plan to halt our
1919
- [Guidelines](#guidelines)
2020
- [Supported versions](#supported-versions)
2121
- [Linting & Code Style](#linting--code-style)
22+
- [Error Codes](#error-codes)
2223
- [Dependency Versions](#dependency-versions)
2324
- [Testing](#testing)
2425
- [Releasing](#releasing)
@@ -100,6 +101,41 @@ However, we've added an extra linting rule: Enforce the use of [strict mode](htt
100101

101102
Using [aegir-lint](#aegir) will help you do this easily; it automatically lints your code.
102103

104+
#### Error Codes
105+
106+
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:
107+
108+
```js
109+
class NotFoundError extends Error {
110+
constructor (message) {
111+
super(message || 'Resource was not found')
112+
this.name = 'NotFoundError'
113+
this.code = NotFoundError.code
114+
}
115+
}
116+
117+
NotFoundError.code = 'ERR_NOT_FOUND'
118+
exports.NotFoundError = NotFoundError
119+
```
120+
121+
122+
This enables others to reuse those definitions and decreases the number of hardcoded values across our codebases.
123+
For example:
124+
125+
```js
126+
const { NotFoundError } = require('some-module')
127+
128+
// throw predefined errors types
129+
if (!value) {
130+
throw new NotFoundError()
131+
}
132+
133+
// compare against code from imported type
134+
if (err.code === NotFoundError.code) {
135+
// handle
136+
}
137+
```
138+
103139
#### Dependency Versions
104140

105141
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.

0 commit comments

Comments
 (0)