@fastify/error 4.0.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,5 +9,5 @@ updates:
9
9
  - package-ecosystem: "npm"
10
10
  directory: "/"
11
11
  schedule:
12
- interval: "weekly"
12
+ interval: "monthly"
13
13
  open-pull-requests-limit: 10
@@ -4,7 +4,6 @@ on:
4
4
  push:
5
5
  branches:
6
6
  - main
7
- - master
8
7
  - next
9
8
  - 'v*'
10
9
  paths-ignore:
@@ -15,9 +14,15 @@ on:
15
14
  - 'docs/**'
16
15
  - '*.md'
17
16
 
17
+ permissions:
18
+ contents: read
19
+
18
20
  jobs:
19
21
  test:
20
- uses: fastify/workflows/.github/workflows/plugins-ci.yml@v4.1.0
22
+ permissions:
23
+ contents: write
24
+ pull-requests: write
25
+ uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5
21
26
  with:
22
27
  license-check: true
23
28
  lint: true
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @fastify/error
2
2
 
3
- ![CI](https://github.com/fastify/fastify-error/workflows/CI/badge.svg)
3
+ [![CI](https://github.com/fastify/fastify-error/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-error/actions/workflows/ci.yml)
4
4
  [![NPM version](https://img.shields.io/npm/v/@fastify/error.svg?style=flat)](https://www.npmjs.com/package/@fastify/error)
5
- [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)
5
+ [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)
6
6
 
7
7
  A small utility, used by Fastify itself, for generating consistent error objects across your codebase and plugins.
8
8
 
@@ -15,14 +15,15 @@ npm i @fastify/error
15
15
 
16
16
  The module exports a function that you can use for consistent error objects, it takes 4 parameters:
17
17
 
18
- ```
19
- createError(code, message [, statusCode [, Base]])
18
+ ```js
19
+ createError(code, message [, statusCode [, Base [, captureStackTrace]]])
20
20
  ```
21
21
 
22
22
  - `code` (`string`, required) - The error code, you can access it later with `error.code`. For consistency, we recommend prefixing plugin error codes with `FST_`
23
23
  - `message` (`string`, required) - The error message. You can also use interpolated strings for formatting the message.
24
24
  - `statusCode` (`number`, optional) - The status code that Fastify will use if the error is sent via HTTP.
25
25
  - `Base` (`ErrorConstructor`, optional) - The base error object that will be used. (eg `TypeError`, `RangeError`)
26
+ - `captureStackTrace` (`boolean`, optional) - Whether to capture the stack trace or not.
26
27
 
27
28
  ```js
28
29
  const createError = require('@fastify/error')
@@ -41,7 +42,7 @@ How to add cause:
41
42
  ```js
42
43
  const createError = require('@fastify/error')
43
44
  const CustomError = createError('ERROR_CODE', 'Hello %s')
44
- console.log(new CustomError('world', {cause: new Error('cause')}))
45
+ console.log(new CustomError('world', {cause: new Error('cause')}))
45
46
  // error.message => 'Hello world'
46
47
  // error.cause => Error('cause')
47
48
  ```
@@ -57,6 +58,83 @@ new CustomError('world')
57
58
  new CustomError(1)
58
59
  ```
59
60
 
61
+ ### instanceof
62
+
63
+ All errors created with `createError` will be instances of the base error constructor you provided, or `Error` if none was provided.
64
+
65
+ ```js
66
+ const createError = require('@fastify/error')
67
+ const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
68
+ const customError = new CustomError('world')
69
+
70
+ console.log(customError instanceof CustomError) // true
71
+ console.log(customError instanceof TypeError) // true
72
+ console.log(customError instanceof Error) // true
73
+ ```
74
+
75
+ All instantiated errors are instances of the `FastifyError` class, which can be required directly from the module.
76
+
77
+ ```js
78
+ const { createError, FastifyError } = require('@fastify/error')
79
+ const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
80
+ const customError = new CustomError('world')
81
+
82
+ console.log(customError instanceof FastifyError) // true
83
+ ```
84
+
85
+ A `FastifyError` created by `createError` can extend another `FastifyError` while maintaining correct `instanceof` behavior.
86
+
87
+ ```js
88
+ const { createError, FastifyError } = require('@fastify/error')
89
+
90
+ const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
91
+ const ChildCustomError = createError('CHILD_ERROR_CODE', 'Hello %s', 500, CustomError)
92
+
93
+ const customError = new ChildCustomError('world')
94
+
95
+ console.log(customError instanceof ChildCustomError) // true
96
+ console.log(customError instanceof CustomError) // true
97
+ console.log(customError instanceof FastifyError) // true
98
+ console.log(customError instanceof TypeError) // true
99
+ console.log(customError instanceof Error) // true
100
+ ```
101
+
102
+ If `fastify-error` is installed multiple times directly or as a transitive dependency, `instanceof` checks for errors created by `createError` will still work correctly across these installations, as long as their error codes (e.g., `FST_ERR_CUSTOM_ERROR`) are identical.
103
+
104
+ ```js
105
+ const { createError, FastifyError } = require('@fastify/error')
106
+
107
+ // CustomError from `@fastify/some-plugin` is created with `createError` and
108
+ // has its own `@fastify/error` installation as dependency. CustomError has
109
+ // FST_ERR_CUSTOM_ERROR as code.
110
+ const { CustomError: CustomErrorFromPlugin } = require('@fastify/some-plugin')
111
+
112
+ const CustomError = createError('FST_ERR_CUSTOM_ERROR', 'Hello %s', 500)
113
+
114
+ const customError = new CustomError('world')
115
+ const customErrorFromPlugin = new CustomErrorFromPlugin('world')
116
+
117
+ console.log(customError instanceof CustomError) // true
118
+ console.log(customError instanceof CustomErrorFromPlugin) // true
119
+ console.log(customErrorFromPlugin instanceof CustomError) // true
120
+ console.log(customErrorFromPlugin instanceof CustomErrorFromPlugin) // true
121
+ ```
122
+
123
+ Changing the code of an instantiated Error will not change the result of the `instanceof` operator.
124
+
125
+ ```js
126
+ const { createError, FastifyError } = require('@fastify/error')
127
+
128
+ const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
129
+ const AnotherCustomError = createError('ANOTHER_ERROR_CODE', 'Hello %s', 500, CustomError)
130
+
131
+ const customError = new CustomError('world')
132
+ customError.code = 'ANOTHER_ERROR_CODE'
133
+
134
+ console.log(customError instanceof CustomError) // true
135
+ console.log(customError instanceof AnotherCustomError) // false
136
+ ```
137
+
60
138
  ## License
61
139
 
62
140
  Licensed under [MIT](./LICENSE).
@@ -0,0 +1,6 @@
1
+ 'use strict'
2
+
3
+ module.exports = require('neostandard')({
4
+ ignores: require('neostandard').resolveIgnoresFromGitignore(),
5
+ ts: true
6
+ })
package/index.js CHANGED
@@ -6,13 +6,23 @@ function toString () {
6
6
  return `${this.name} [${this.code}]: ${this.message}`
7
7
  }
8
8
 
9
- function createError (code, message, statusCode = 500, Base = Error) {
9
+ const FastifyGenericErrorSymbol = Symbol.for('fastify-error-generic')
10
+
11
+ function createError (code, message, statusCode = 500, Base = Error, captureStackTrace = createError.captureStackTrace) {
12
+ const shouldCreateFastifyGenericError = code === FastifyGenericErrorSymbol
13
+
14
+ if (shouldCreateFastifyGenericError) {
15
+ code = 'FST_ERR'
16
+ }
17
+
10
18
  if (!code) throw new Error('Fastify error code must not be empty')
11
19
  if (!message) throw new Error('Fastify error message must not be empty')
12
20
 
13
21
  code = code.toUpperCase()
14
22
  !statusCode && (statusCode = undefined)
15
23
 
24
+ const FastifySpecificErrorSymbol = Symbol.for(`fastify-error ${code}`)
25
+
16
26
  function FastifyError (...args) {
17
27
  if (!new.target) {
18
28
  return new FastifyError(...args)
@@ -29,7 +39,7 @@ function createError (code, message, statusCode = 500, Base = Error) {
29
39
 
30
40
  this.message = format(message, ...args)
31
41
 
32
- Error.stackTraceLimit !== 0 && Error.captureStackTrace(this, FastifyError)
42
+ Error.stackTraceLimit && captureStackTrace && Error.captureStackTrace(this, FastifyError)
33
43
  }
34
44
 
35
45
  FastifyError.prototype = Object.create(Base.prototype, {
@@ -38,9 +48,41 @@ function createError (code, message, statusCode = 500, Base = Error) {
38
48
  enumerable: false,
39
49
  writable: true,
40
50
  configurable: true
51
+ },
52
+ [FastifyGenericErrorSymbol]: {
53
+ value: true,
54
+ enumerable: false,
55
+ writable: false,
56
+ configurable: false
57
+ },
58
+ [FastifySpecificErrorSymbol]: {
59
+ value: true,
60
+ enumerable: false,
61
+ writable: false,
62
+ configurable: false
41
63
  }
42
64
  })
43
65
 
66
+ if (shouldCreateFastifyGenericError) {
67
+ Object.defineProperty(FastifyError, Symbol.hasInstance, {
68
+ value (instance) {
69
+ return instance && instance[FastifyGenericErrorSymbol]
70
+ },
71
+ configurable: false,
72
+ writable: false,
73
+ enumerable: false
74
+ })
75
+ } else {
76
+ Object.defineProperty(FastifyError, Symbol.hasInstance, {
77
+ value (instance) {
78
+ return instance && instance[FastifySpecificErrorSymbol]
79
+ },
80
+ configurable: false,
81
+ writable: false,
82
+ enumerable: false
83
+ })
84
+ }
85
+
44
86
  FastifyError.prototype[Symbol.toStringTag] = 'Error'
45
87
 
46
88
  FastifyError.prototype.toString = toString
@@ -48,6 +90,11 @@ function createError (code, message, statusCode = 500, Base = Error) {
48
90
  return FastifyError
49
91
  }
50
92
 
93
+ createError.captureStackTrace = true
94
+
95
+ const FastifyErrorConstructor = createError(FastifyGenericErrorSymbol, 'Fastify Error', 500, Error)
96
+
51
97
  module.exports = createError
98
+ module.exports.FastifyError = FastifyErrorConstructor
52
99
  module.exports.default = createError
53
100
  module.exports.createError = createError
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@fastify/error",
3
- "version": "4.0.0",
3
+ "version": "4.2.0",
4
4
  "description": "A small utility, used by Fastify itself, for generating consistent error objects across your codebase and plugins.",
5
5
  "main": "index.js",
6
6
  "type": "commonjs",
7
7
  "types": "types/index.d.ts",
8
8
  "scripts": {
9
- "lint": "standard",
10
- "lint:fix": "standard --fix",
9
+ "lint": "eslint",
10
+ "lint:fix": "eslint --fix",
11
11
  "test": "npm run test:unit && npm run test:typescript",
12
- "test:unit": "tap",
12
+ "test:unit": "c8 --100 node --test",
13
13
  "test:typescript": "tsd"
14
14
  },
15
15
  "repository": {
@@ -23,16 +23,46 @@
23
23
  "plugin"
24
24
  ],
25
25
  "author": "Tomas Della Vedova",
26
+ "contributors": [
27
+ {
28
+ "name": "Matteo Collina",
29
+ "email": "hello@matteocollina.com"
30
+ },
31
+ {
32
+ "name": "James Sumners",
33
+ "url": "https://james.sumners.info"
34
+ },
35
+ {
36
+ "name": "Aras Abbasi",
37
+ "email": "aras.abbasi@gmail.com"
38
+ },
39
+ {
40
+ "name": "Frazer Smith",
41
+ "email": "frazer.dev@icloud.com",
42
+ "url": "https://github.com/fdawgs"
43
+ }
44
+ ],
26
45
  "license": "MIT",
27
46
  "bugs": {
28
47
  "url": "https://github.com/fastify/fastify-error/issues"
29
48
  },
30
49
  "homepage": "https://github.com/fastify/fastify-error#readme",
50
+ "funding": [
51
+ {
52
+ "type": "github",
53
+ "url": "https://github.com/sponsors/fastify"
54
+ },
55
+ {
56
+ "type": "opencollective",
57
+ "url": "https://opencollective.com/fastify"
58
+ }
59
+ ],
31
60
  "devDependencies": {
32
61
  "benchmark": "^2.1.4",
33
- "standard": "^17.1.0",
34
- "tap": "^18.7.1",
35
- "tsd": "^0.31.0"
62
+ "c8": "^10.1.2",
63
+ "eslint": "^9.17.0",
64
+ "neostandard": "^0.12.0",
65
+ "tsd": "^0.32.0"
36
66
  },
37
67
  "tsd": {
38
68
  "compilerOptions": {
@@ -1,40 +1,40 @@
1
1
  'use strict'
2
2
 
3
- const { test } = require('tap')
4
- const createError = require('..')
3
+ const test = require('node:test')
4
+ const { createError, FastifyError } = require('..')
5
5
 
6
- test('Create error with zero parameter', t => {
6
+ test('Create error with zero parameter', (t) => {
7
7
  t.plan(6)
8
8
 
9
9
  const NewError = createError('CODE', 'Not available')
10
10
  const err = new NewError()
11
- t.ok(err instanceof Error)
12
- t.equal(err.name, 'FastifyError')
13
- t.equal(err.message, 'Not available')
14
- t.equal(err.code, 'CODE')
15
- t.equal(err.statusCode, 500)
16
- t.ok(err.stack)
11
+ t.assert.ok(err instanceof Error)
12
+ t.assert.equal(err.name, 'FastifyError')
13
+ t.assert.equal(err.message, 'Not available')
14
+ t.assert.equal(err.code, 'CODE')
15
+ t.assert.equal(err.statusCode, 500)
16
+ t.assert.ok(err.stack)
17
17
  })
18
18
 
19
- test('Create error with 1 parameter', t => {
19
+ test('Create error with 1 parameter', (t) => {
20
20
  t.plan(6)
21
21
 
22
22
  const NewError = createError('CODE', 'hey %s')
23
23
  const err = new NewError('alice')
24
- t.ok(err instanceof Error)
25
- t.equal(err.name, 'FastifyError')
26
- t.equal(err.message, 'hey alice')
27
- t.equal(err.code, 'CODE')
28
- t.equal(err.statusCode, 500)
29
- t.ok(err.stack)
24
+ t.assert.equal(err.name, 'FastifyError')
25
+ t.assert.ok(err instanceof Error)
26
+ t.assert.equal(err.message, 'hey alice')
27
+ t.assert.equal(err.code, 'CODE')
28
+ t.assert.equal(err.statusCode, 500)
29
+ t.assert.ok(err.stack)
30
30
  })
31
31
 
32
- test('Create error with 1 parameter set to undefined', t => {
32
+ test('Create error with 1 parameter set to undefined', (t) => {
33
33
  t.plan(1)
34
34
 
35
35
  const NewError = createError('CODE', 'hey %s')
36
36
  const err = new NewError(undefined)
37
- t.equal(err.message, 'hey undefined')
37
+ t.assert.equal(err.message, 'hey undefined')
38
38
  })
39
39
 
40
40
  test('Create error with 2 parameters', (t) => {
@@ -42,143 +42,191 @@ test('Create error with 2 parameters', (t) => {
42
42
 
43
43
  const NewError = createError('CODE', 'hey %s, I like your %s')
44
44
  const err = new NewError('alice', 'attitude')
45
- t.ok(err instanceof Error)
46
- t.equal(err.name, 'FastifyError')
47
- t.equal(err.message, 'hey alice, I like your attitude')
48
- t.equal(err.code, 'CODE')
49
- t.equal(err.statusCode, 500)
50
- t.ok(err.stack)
45
+ t.assert.ok(err instanceof Error)
46
+ t.assert.equal(err.name, 'FastifyError')
47
+ t.assert.equal(err.message, 'hey alice, I like your attitude')
48
+ t.assert.equal(err.code, 'CODE')
49
+ t.assert.equal(err.statusCode, 500)
50
+ t.assert.ok(err.stack)
51
51
  })
52
52
 
53
- test('Create error with 2 parameters set to undefined', t => {
53
+ test('Create error with 2 parameters set to undefined', (t) => {
54
54
  t.plan(1)
55
55
 
56
56
  const NewError = createError('CODE', 'hey %s, I like your %s')
57
57
  const err = new NewError(undefined, undefined)
58
- t.equal(err.message, 'hey undefined, I like your undefined')
58
+ t.assert.equal(err.message, 'hey undefined, I like your undefined')
59
59
  })
60
60
 
61
- test('Create error with 3 parameters', t => {
61
+ test('Create error with 3 parameters', (t) => {
62
62
  t.plan(6)
63
63
 
64
64
  const NewError = createError('CODE', 'hey %s, I like your %s %s')
65
65
  const err = new NewError('alice', 'attitude', 'see you')
66
- t.ok(err instanceof Error)
67
- t.equal(err.name, 'FastifyError')
68
- t.equal(err.message, 'hey alice, I like your attitude see you')
69
- t.equal(err.code, 'CODE')
70
- t.equal(err.statusCode, 500)
71
- t.ok(err.stack)
66
+ t.assert.ok(err instanceof Error)
67
+ t.assert.equal(err.name, 'FastifyError')
68
+ t.assert.equal(err.message, 'hey alice, I like your attitude see you')
69
+ t.assert.equal(err.code, 'CODE')
70
+ t.assert.equal(err.statusCode, 500)
71
+ t.assert.ok(err.stack)
72
72
  })
73
73
 
74
- test('Create error with 3 parameters set to undefined', t => {
74
+ test('Create error with 3 parameters set to undefined', (t) => {
75
75
  t.plan(4)
76
76
 
77
77
  const NewError = createError('CODE', 'hey %s, I like your %s %s')
78
78
  const err = new NewError(undefined, undefined, undefined)
79
- t.equal(err.message, 'hey undefined, I like your undefined undefined')
80
- t.equal(err.code, 'CODE')
81
- t.equal(err.statusCode, 500)
82
- t.ok(err.stack)
79
+ t.assert.equal(err.message, 'hey undefined, I like your undefined undefined')
80
+ t.assert.equal(err.code, 'CODE')
81
+ t.assert.equal(err.statusCode, 500)
82
+ t.assert.ok(err.stack)
83
83
  })
84
84
 
85
- test('Create error with 4 parameters set to undefined', t => {
85
+ test('Create error with 4 parameters set to undefined', (t) => {
86
86
  t.plan(4)
87
87
 
88
88
  const NewError = createError('CODE', 'hey %s, I like your %s %s and %s')
89
89
  const err = new NewError(undefined, undefined, undefined, undefined)
90
- t.equal(err.message, 'hey undefined, I like your undefined undefined and undefined')
91
- t.equal(err.code, 'CODE')
92
- t.equal(err.statusCode, 500)
93
- t.ok(err.stack)
90
+ t.assert.equal(
91
+ err.message,
92
+ 'hey undefined, I like your undefined undefined and undefined'
93
+ )
94
+ t.assert.equal(err.code, 'CODE')
95
+ t.assert.equal(err.statusCode, 500)
96
+ t.assert.ok(err.stack)
94
97
  })
95
98
 
96
- test('Create error with no statusCode property', t => {
99
+ test('Create error with no statusCode property', (t) => {
97
100
  t.plan(6)
98
101
 
99
102
  const NewError = createError('CODE', 'hey %s', 0)
100
103
  const err = new NewError('dude')
101
- t.ok(err instanceof Error)
102
- t.equal(err.name, 'FastifyError')
103
- t.equal(err.message, 'hey dude')
104
- t.equal(err.code, 'CODE')
105
- t.equal(err.statusCode, undefined)
106
- t.ok(err.stack)
104
+ t.assert.ok(err instanceof Error)
105
+ t.assert.equal(err.name, 'FastifyError')
106
+ t.assert.equal(err.message, 'hey dude')
107
+ t.assert.equal(err.code, 'CODE')
108
+ t.assert.equal(err.statusCode, undefined)
109
+ t.assert.ok(err.stack)
107
110
  })
108
111
 
109
- test('Should throw when error code has no fastify code', t => {
112
+ test('Should throw when error code has no fastify code', (t) => {
110
113
  t.plan(1)
114
+ t.assert.throws(
115
+ () => createError(),
116
+ new Error('Fastify error code must not be empty')
117
+ )
118
+ })
111
119
 
112
- t.throws(() => createError(), new Error('Fastify error code must not be empty'))
120
+ test('Should throw when error code has no message', (t) => {
121
+ t.assert.throws(
122
+ () => createError('code'),
123
+ new Error('Fastify error message must not be empty')
124
+ )
113
125
  })
114
126
 
115
- test('Should throw when error code has no message', t => {
116
- t.plan(1)
127
+ test('Create error with different base', (t) => {
128
+ t.plan(7)
117
129
 
118
- t.throws(() => createError('code'), new Error('Fastify error message must not be empty'))
130
+ const NewError = createError('CODE', 'hey %s', 500, TypeError)
131
+ const err = new NewError('dude')
132
+ t.assert.ok(err instanceof Error)
133
+ t.assert.ok(err instanceof TypeError)
134
+ t.assert.equal(err.name, 'FastifyError')
135
+ t.assert.equal(err.message, 'hey dude')
136
+ t.assert.equal(err.code, 'CODE')
137
+ t.assert.equal(err.statusCode, 500)
138
+ t.assert.ok(err.stack)
119
139
  })
120
140
 
121
- test('Create error with different base', t => {
141
+ test('Create error with different base (no stack) (global)', (t) => {
122
142
  t.plan(7)
123
143
 
144
+ createError.captureStackTrace = false
124
145
  const NewError = createError('CODE', 'hey %s', 500, TypeError)
125
146
  const err = new NewError('dude')
126
- t.ok(err instanceof Error)
127
- t.ok(err instanceof TypeError)
128
- t.equal(err.name, 'FastifyError')
129
- t.equal(err.message, 'hey dude')
130
- t.equal(err.code, 'CODE')
131
- t.equal(err.statusCode, 500)
132
- t.ok(err.stack)
147
+ t.assert.ok(err instanceof Error)
148
+ t.assert.ok(err instanceof TypeError)
149
+ t.assert.equal(err.name, 'FastifyError')
150
+ t.assert.equal(err.message, 'hey dude')
151
+ t.assert.equal(err.code, 'CODE')
152
+ t.assert.equal(err.statusCode, 500)
153
+ t.assert.equal(err.stack, undefined)
154
+ createError.captureStackTrace = true
155
+ })
156
+
157
+ test('Create error with different base (no stack) (parameter)', (t) => {
158
+ t.plan(7)
159
+
160
+ const NewError = createError('CODE', 'hey %s', 500, TypeError, false)
161
+ const err = new NewError('dude')
162
+ t.assert.ok(err instanceof Error)
163
+ t.assert.ok(err instanceof TypeError)
164
+ t.assert.equal(err.name, 'FastifyError')
165
+ t.assert.equal(err.message, 'hey dude')
166
+ t.assert.equal(err.code, 'CODE')
167
+ t.assert.equal(err.statusCode, 500)
168
+ t.assert.equal(err.stack, undefined)
133
169
  })
134
170
 
135
- test('FastifyError.toString returns code', t => {
171
+ test('FastifyError.toString returns code', (t) => {
136
172
  t.plan(1)
137
173
 
138
174
  const NewError = createError('CODE', 'foo')
139
175
  const err = new NewError()
140
- t.equal(err.toString(), 'FastifyError [CODE]: foo')
176
+ t.assert.equal(err.toString(), 'FastifyError [CODE]: foo')
141
177
  })
142
178
 
143
- test('Create the error without the new keyword', t => {
179
+ test('Create the error without the new keyword', (t) => {
144
180
  t.plan(6)
145
181
 
146
182
  const NewError = createError('CODE', 'Not available')
147
183
  const err = NewError()
148
- t.ok(err instanceof Error)
149
- t.equal(err.name, 'FastifyError')
150
- t.equal(err.message, 'Not available')
151
- t.equal(err.code, 'CODE')
152
- t.equal(err.statusCode, 500)
153
- t.ok(err.stack)
184
+ t.assert.ok(err instanceof Error)
185
+ t.assert.equal(err.name, 'FastifyError')
186
+ t.assert.equal(err.message, 'Not available')
187
+ t.assert.equal(err.code, 'CODE')
188
+ t.assert.equal(err.statusCode, 500)
189
+ t.assert.ok(err.stack)
154
190
  })
155
191
 
156
- test('Create an error with cause', t => {
192
+ test('Create an error with cause', (t) => {
157
193
  t.plan(2)
194
+
158
195
  const cause = new Error('HEY')
159
196
  const NewError = createError('CODE', 'Not available')
160
197
  const err = NewError({ cause })
161
198
 
162
- t.ok(err instanceof Error)
163
- t.equal(err.cause, cause)
199
+ t.assert.ok(err instanceof Error)
200
+ t.assert.equal(err.cause, cause)
164
201
  })
165
202
 
166
- test('Create an error with cause and message', t => {
203
+ test('Create an error with cause and message', (t) => {
167
204
  t.plan(2)
205
+
168
206
  const cause = new Error('HEY')
169
207
  const NewError = createError('CODE', 'Not available: %s')
170
208
  const err = NewError('foo', { cause })
171
209
 
172
- t.ok(err instanceof Error)
173
- t.equal(err.cause, cause)
210
+ t.assert.ok(err instanceof Error)
211
+ t.assert.equal(err.cause, cause)
174
212
  })
175
213
 
176
- test('Create an error with last argument null', t => {
214
+ test('Create an error with last argument null', (t) => {
177
215
  t.plan(2)
216
+
178
217
  const cause = new Error('HEY')
179
218
  const NewError = createError('CODE', 'Not available')
180
219
  const err = NewError({ cause }, null)
181
220
 
182
- t.ok(err instanceof Error)
183
- t.notOk(err.cause)
221
+ t.assert.ok(err instanceof Error)
222
+ t.assert.ifError(err.cause)
223
+ })
224
+
225
+ test('check if FastifyError is instantiable', (t) => {
226
+ t.plan(2)
227
+
228
+ const err = new FastifyError()
229
+
230
+ t.assert.ok(err instanceof FastifyError)
231
+ t.assert.ok(err instanceof Error)
184
232
  })
@@ -0,0 +1,263 @@
1
+ 'use strict'
2
+
3
+ const cp = require('node:child_process')
4
+ const fs = require('node:fs')
5
+ const path = require('node:path')
6
+ const os = require('node:os')
7
+ const test = require('node:test')
8
+ const { createError, FastifyError } = require('..')
9
+
10
+ test('Readme: All errors created with `createError` will be instances of the base error constructor you provided, or `Error` if none was provided.', (t) => {
11
+ t.plan(3)
12
+
13
+ const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
14
+ const customError = new CustomError('world')
15
+
16
+ t.assert.ok(customError instanceof CustomError)
17
+ t.assert.ok(customError instanceof TypeError)
18
+ t.assert.ok(customError instanceof Error)
19
+ })
20
+
21
+ test('Readme: All instantiated errors will be instances of the `FastifyError` class. The `FastifyError` class can be required from the module directly.', (t) => {
22
+ t.plan(1)
23
+
24
+ const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
25
+ const customError = new CustomError('world')
26
+
27
+ t.assert.ok(customError instanceof FastifyError)
28
+ })
29
+
30
+ test('Readme: It is possible to create a `FastifyError` that extends another `FastifyError`, created by `createError`, while instanceof working correctly.', (t) => {
31
+ t.plan(5)
32
+
33
+ const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
34
+ const ChildCustomError = createError('CHILD_ERROR_CODE', 'Hello %s', 500, CustomError)
35
+
36
+ const customError = new ChildCustomError('world')
37
+
38
+ t.assert.ok(customError instanceof ChildCustomError)
39
+ t.assert.ok(customError instanceof CustomError)
40
+ t.assert.ok(customError instanceof FastifyError)
41
+ t.assert.ok(customError instanceof TypeError)
42
+ t.assert.ok(customError instanceof Error)
43
+ })
44
+
45
+ test('Readme: Changing the code of an instantiated Error will not change the result of the `instanceof` operator.', (t) => {
46
+ t.plan(3)
47
+
48
+ const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
49
+ const AnotherCustomError = createError('ANOTHER_ERROR_CODE', 'Hello %s', 500, CustomError)
50
+
51
+ const customError = new CustomError('world')
52
+ customError.code = 'ANOTHER_ERROR_CODE'
53
+
54
+ t.assert.ok(customError instanceof CustomError)
55
+ t.assert.ok(customError instanceof AnotherCustomError === false)
56
+ t.assert.ok(customError instanceof FastifyError)
57
+ })
58
+
59
+ test('check if createError creates an Error which is instanceof Error', (t) => {
60
+ t.plan(3)
61
+
62
+ const CustomFastifyError = createError('CODE', 'Not available')
63
+ const err = CustomFastifyError()
64
+
65
+ t.assert.ok(err instanceof Error)
66
+ t.assert.ok(err instanceof SyntaxError === false)
67
+ t.assert.ok(err instanceof TypeError === false)
68
+ })
69
+
70
+ test('check if createError creates an Error which is instanceof FastifyError', (t) => {
71
+ t.plan(4)
72
+
73
+ const CustomFastifyError = createError('CODE', 'Not available')
74
+ const err = CustomFastifyError()
75
+
76
+ t.assert.ok(err instanceof Error)
77
+ t.assert.ok(err instanceof FastifyError)
78
+ t.assert.ok(err instanceof SyntaxError === false)
79
+ t.assert.ok(err instanceof TypeError === false)
80
+ })
81
+
82
+ test('check if createError creates an Error with the right BaseConstructor', (t) => {
83
+ t.plan(2)
84
+
85
+ const CustomFastifyError = createError('CODE', 'Not available', 500, TypeError)
86
+ const err = CustomFastifyError()
87
+
88
+ t.assert.ok(err instanceof Error)
89
+ t.assert.ok(err instanceof TypeError)
90
+ })
91
+
92
+ test('check if createError creates an Error with the right BaseConstructor, which is a FastifyError', (t) => {
93
+ t.plan(6)
94
+
95
+ const BaseFastifyError = createError('CODE', 'Not available', 500, TypeError)
96
+ const CustomFastifyError = createError('CODE', 'Not available', 500, BaseFastifyError)
97
+ const err = CustomFastifyError()
98
+
99
+ t.assert.ok(err instanceof Error)
100
+ t.assert.ok(err instanceof TypeError)
101
+ t.assert.ok(err instanceof FastifyError)
102
+ t.assert.ok(err instanceof BaseFastifyError)
103
+ t.assert.ok(err instanceof CustomFastifyError)
104
+ t.assert.ok(err instanceof SyntaxError === false)
105
+ })
106
+
107
+ // for more information see https://github.com/fastify/fastify-error/pull/86#issuecomment-1301466407
108
+ test('ensure that instanceof works accross different installations of the fastify-error module', async (t) => {
109
+ const assertsPlanned = 5
110
+ t.plan(assertsPlanned)
111
+
112
+ // We need to create a test environment where fastify-error is installed in two different locations
113
+ // and then we will check if the error created in one location is instanceof the error created in the other location
114
+ // This is done by creating a test directory with the following structure:
115
+
116
+ // /
117
+ // ├── index.js
118
+ // └── node_modules/
119
+ // ├── fastify-error/
120
+ // │ └── index.js
121
+ // └── dep/
122
+ // ├── index.js
123
+ // └── node_modules/
124
+ // └── fastify-error/
125
+ // └── index.js
126
+
127
+ const testDirectoryPrefix = 'fastify-error-instanceof-test-'
128
+
129
+ const testCwd = path.resolve(os.tmpdir(), `${testDirectoryPrefix}${Math.random().toString(36).substring(2, 15)}`)
130
+ fs.mkdirSync(testCwd, { recursive: true })
131
+
132
+ // Create the index.js. It will be executed as a forked process, so we need to
133
+ // use process.send to send messages back to the parent process.
134
+ fs.writeFileSync(path.resolve(testCwd, 'index.js'), `
135
+ 'use strict'
136
+
137
+ const path = require('node:path')
138
+ const { createError, FastifyError } = require('fastify-error')
139
+ const { foo } = require('dep')
140
+
141
+ const actualPathOfFastifyError = require.resolve('fastify-error')
142
+ const expectedPathOfFastifyError = path.resolve('node_modules', 'fastify-error', 'index.js')
143
+
144
+ // Ensure that fastify-error is required from the node_modules directory of the test-project
145
+ if (actualPathOfFastifyError !== expectedPathOfFastifyError) {
146
+ console.error('actualPathOfFastifyError', actualPathOfFastifyError)
147
+ console.error('expectedPathOfFastifyError', expectedPathOfFastifyError)
148
+ throw new Error('fastify-error should be required from the node_modules directory of the test-project')
149
+ }
150
+
151
+ const Boom = createError('Boom', 'Boom', 500)
152
+ const ChildBoom = createError('ChildBoom', 'Boom', 500, Boom)
153
+ const NotChildBoom = createError('NotChildBoom', 'NotChildBoom', 500, Boom)
154
+
155
+ try {
156
+ foo()
157
+ } catch (err) {
158
+ process.send(err instanceof Error)
159
+ process.send(err instanceof FastifyError)
160
+ process.send(err instanceof NotChildBoom)
161
+ process.send(err instanceof Boom)
162
+ process.send(err instanceof ChildBoom)
163
+ }
164
+ `)
165
+
166
+ // Create /node_modules/fastify-error directory
167
+ // Copy the index.js file to the fastify-error directory
168
+ fs.mkdirSync(path.resolve(testCwd, 'node_modules', 'fastify-error'), { recursive: true })
169
+ fs.copyFileSync(path.resolve(process.cwd(), 'index.js'), path.resolve(testCwd, 'node_modules', 'fastify-error', 'index.js'))
170
+
171
+ // Create /node_modules/dep/node_modules/fastify-error directory
172
+ // Copy the index.js to the fastify-error directory
173
+ fs.mkdirSync(path.resolve(testCwd, 'node_modules', 'dep', 'node_modules', 'fastify-error'), { recursive: true })
174
+ fs.copyFileSync(path.resolve(process.cwd(), 'index.js'), path.resolve(testCwd, 'node_modules', 'dep', 'node_modules', 'fastify-error', 'index.js'))
175
+
176
+ // Create /node_modules/dep/index.js. It will export a function foo which will
177
+ // throw an error when called. The error will be an instance of ChildBoom, created
178
+ // by the fastify-error module in the node_modules directory of dep.
179
+ fs.writeFileSync(path.resolve(testCwd, 'node_modules', 'dep', 'index.js'), `
180
+ 'use strict'
181
+
182
+ const path = require('node:path')
183
+ const { createError } = require('fastify-error')
184
+
185
+ const actualPathOfFastifyError = require.resolve('fastify-error')
186
+ const expectedPathOfFastifyError = path.resolve('node_modules', 'dep', 'node_modules', 'fastify-error', 'index.js')
187
+
188
+ // Ensure that fastify-error is required from the node_modules directory of the test-project
189
+ if (actualPathOfFastifyError !== expectedPathOfFastifyError) {
190
+ console.error('actualPathOfFastifyError', actualPathOfFastifyError)
191
+ console.error('expectedPathOfFastifyError', expectedPathOfFastifyError)
192
+ throw new Error('fastify-error should be required from the node_modules directory of dep')
193
+ }
194
+
195
+ const Boom = createError('Boom', 'Boom', 500)
196
+ const ChildBoom = createError('ChildBoom', 'Boom', 500, Boom)
197
+
198
+ module.exports.foo = function foo () {
199
+ throw new ChildBoom('foo go Boom')
200
+ }
201
+ `)
202
+
203
+ const finishedPromise = {
204
+ promise: undefined,
205
+ reject: undefined,
206
+ resolve: undefined,
207
+ }
208
+
209
+ finishedPromise.promise = new Promise((resolve, reject) => {
210
+ finishedPromise.resolve = resolve
211
+ finishedPromise.reject = reject
212
+ })
213
+
214
+ const child = cp.fork(path.resolve(testCwd, 'index.js'), {
215
+ cwd: testCwd,
216
+ stdio: 'inherit',
217
+ env: {
218
+ ...process.env,
219
+ NODE_OPTIONS: '--no-warnings'
220
+ },
221
+ })
222
+
223
+ let messageCount = 0
224
+ child.on('message', message => {
225
+ try {
226
+ switch (messageCount) {
227
+ case 0:
228
+ t.assert.strictEqual(message, true, 'instanceof Error')
229
+ break
230
+ case 1:
231
+ t.assert.strictEqual(message, true, 'instanceof FastifyError')
232
+ break
233
+ case 2:
234
+ t.assert.strictEqual(message, false, 'instanceof NotChildBoom')
235
+ break
236
+ case 3:
237
+ t.assert.strictEqual(message, true, 'instanceof Boom')
238
+ break
239
+ case 4:
240
+ t.assert.strictEqual(message, true, 'instanceof ChildBoom')
241
+ break
242
+ }
243
+ if (++messageCount === assertsPlanned) {
244
+ finishedPromise.resolve()
245
+ }
246
+ } catch (err) {
247
+ finishedPromise.reject(err)
248
+ }
249
+ })
250
+
251
+ child.on('error', err => {
252
+ finishedPromise.reject(err)
253
+ })
254
+
255
+ await finishedPromise.promise
256
+
257
+ // Cleanup
258
+ // As we are creating the test-setup on the fly in the /tmp directory, we can remove it
259
+ // safely when we are done. It is not relevant for the test if the deletion fails.
260
+ try {
261
+ fs.rmSync(testCwd, { recursive: true, force: true })
262
+ } catch {}
263
+ })
package/types/index.d.ts CHANGED
@@ -2,21 +2,24 @@ declare function createError<C extends string, SC extends number, Arg extends un
2
2
  code: C,
3
3
  message: string,
4
4
  statusCode: SC,
5
- Base?: ErrorConstructor
5
+ Base?: ErrorConstructor,
6
+ captureStackTrace?: boolean
6
7
  ): createError.FastifyErrorConstructor<{ code: C, statusCode: SC }, Arg>
7
8
 
8
9
  declare function createError<C extends string, Arg extends unknown[] = [any?, any?, any?]> (
9
10
  code: C,
10
11
  message: string,
11
12
  statusCode?: number,
12
- Base?: ErrorConstructor
13
+ Base?: ErrorConstructor,
14
+ captureStackTrace?: boolean
13
15
  ): createError.FastifyErrorConstructor<{ code: C }, Arg>
14
16
 
15
17
  declare function createError<Arg extends unknown[] = [any?, any?, any?]> (
16
18
  code: string,
17
19
  message: string,
18
20
  statusCode?: number,
19
- Base?: ErrorConstructor
21
+ Base?: ErrorConstructor,
22
+ captureStackTrace?: boolean
20
23
  ): createError.FastifyErrorConstructor<{ code: string }, Arg>
21
24
 
22
25
  type CreateError = typeof createError
@@ -37,6 +40,8 @@ declare namespace createError {
37
40
  readonly prototype: FastifyError & E
38
41
  }
39
42
 
43
+ export const FastifyError: FastifyErrorConstructor
44
+
40
45
  export const createError: CreateError
41
46
  export { createError as default }
42
47
  }
@@ -9,6 +9,14 @@ expectType<'ERROR_CODE'>(err.code)
9
9
  expectType<string>(err.message)
10
10
  expectType<number | undefined>(err.statusCode)
11
11
 
12
+ const CustomErrorNoStackTrace = createError('ERROR_CODE', 'message', undefined, undefined, false)
13
+ expectType<FastifyErrorConstructor<{ code: 'ERROR_CODE' }>>(CustomErrorNoStackTrace)
14
+ const errNoStackTrace = new CustomErrorNoStackTrace()
15
+ expectType<FastifyError & { code: 'ERROR_CODE' }>(errNoStackTrace)
16
+ expectType<'ERROR_CODE'>(errNoStackTrace.code)
17
+ expectType<string>(errNoStackTrace.message)
18
+ expectType<number | undefined>(errNoStackTrace.statusCode)
19
+
12
20
  const CustomTypedError = createError('OTHER_CODE', 'message', 400)
13
21
  expectType<FastifyErrorConstructor<{ code: 'OTHER_CODE', statusCode: 400 }>>(CustomTypedError)
14
22
  const typed = new CustomTypedError()
@@ -66,7 +74,19 @@ expectError(new CustomTypedArgError6('a', 'b', 'c'))
66
74
  CustomTypedArgError6('a', 'b', 'c', 'd')
67
75
  expectError(new CustomTypedArgError6('a', 'b', 'c', 'd', 'e'))
68
76
 
69
-
70
77
  const CustomErrorWithErrorConstructor = createError('ERROR_CODE', 'message', 500, TypeError)
71
78
  expectType<FastifyErrorConstructor<{ code: 'ERROR_CODE', statusCode: 500 }>>(CustomErrorWithErrorConstructor)
72
- CustomErrorWithErrorConstructor({cause: new Error('Error')})
79
+ CustomErrorWithErrorConstructor({ cause: new Error('Error') })
80
+ const customErrorWithErrorConstructor = CustomErrorWithErrorConstructor()
81
+ if (customErrorWithErrorConstructor instanceof FastifyError) {
82
+ expectType<'ERROR_CODE'>(customErrorWithErrorConstructor.code)
83
+ expectType<string>(customErrorWithErrorConstructor.message)
84
+ expectType<500>(customErrorWithErrorConstructor.statusCode)
85
+ }
86
+
87
+ const error = new FastifyError('ERROR_CODE', 'message', 500)
88
+ if (error instanceof FastifyError) {
89
+ expectType<string>(error.code)
90
+ expectType<string>(error.message)
91
+ expectType<number | undefined>(error.statusCode)
92
+ }
package/.taprc DELETED
@@ -1,2 +0,0 @@
1
- files:
2
- - test/**/*.test.js