Skip to content

Commit d14a10f

Browse files
authored
fastify#4521 Replace native errors with @fastify/errors (fastify#4554)
1 parent c7d8d20 commit d14a10f

15 files changed

+314
-52
lines changed

docs/Reference/Errors.md

Lines changed: 110 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,43 @@ fastify.listen({ port: 3000 }, function (err, address) {
133133

134134
404 Not Found.
135135

136+
#### FST_ERR_OPTIONS_NOT_OBJ
137+
<a id="FST_ERR_OPTIONS_NOT_OBJ"></a>
138+
139+
Fastify options must be an object.
140+
141+
#### FST_ERR_QSP_NOT_FN
142+
<a id="FST_ERR_QSP_NOT_FN"></a>
143+
144+
QueryStringParser option should be a function.
145+
146+
#### FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN
147+
<a id="FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN"></a>
148+
149+
SchemaController.bucket option should be a function.
150+
151+
#### FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN
152+
<a id="FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN"></a>
153+
154+
SchemaErrorFormatter option should be a non async function.
155+
156+
#### FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ
157+
<a id="FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ"></a>
158+
159+
ajv.customOptions option should be an object.
160+
161+
#### FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR
162+
<a id="FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR"></a>
163+
164+
ajv.plugins option should be an array.
165+
166+
#### FST_ERR_VERSION_CONSTRAINT_NOT_STR
167+
<a id="FST_ERR_VERSION_CONSTRAINT_NOT_STR"></a>
168+
169+
Version constraint should be a string.
170+
136171
<a name="FST_ERR_CTP_ALREADY_PRESENT"></a>
172+
137173
#### FST_ERR_CTP_ALREADY_PRESENT
138174
<a id="FST_ERR_CTP_ALREADY_PRESENT"></a>
139175

@@ -184,6 +220,16 @@ Request body size did not match `Content-Length`.
184220

185221
Body cannot be empty when content-type is set to `application/json`.
186222

223+
#### FST_ERR_CTP_INSTANCE_ALREADY_STARTED
224+
<a id="FST_ERR_CTP_INSTANCE_ALREADY_STARTED"></a>
225+
226+
Fastify is already started.
227+
228+
#### FST_ERR_INSTANCE_ALREADY_LISTENING
229+
<a id="FST_ERR_INSTANCE_ALREADY_LISTENING"></a>
230+
231+
Fastify instance is already listening.
232+
187233
#### FST_ERR_DEC_ALREADY_PRESENT
188234
<a id="FST_ERR_DEC_ALREADY_PRESENT"></a>
189235

@@ -214,10 +260,15 @@ The hook name must be a string.
214260

215261
The hook callback must be a function.
216262

263+
#### FST_ERR_HOOK_NOT_SUPPORTED
264+
<a id="FST_ERR_HOOK_NOT_SUPPORTED"></a>
265+
266+
The hook is not supported.
267+
217268
#### FST_ERR_MISSING_MIDDLEWARE
218269
<a id="FST_ERR_MISSING_MIDDLEWARE"></a>
219270

220-
You must register a plugin for handling middlewares,
271+
You must register a plugin for handling middlewares,
221272
visit [`Middleware`](./Middleware.md) for more info.
222273

223274
<a name="FST_ERR_HOOK_TIMEOUT"></a>
@@ -278,7 +329,7 @@ Missing serialization function.
278329
#### FST_ERR_REQ_INVALID_VALIDATION_INVOCATION
279330
<a id="FST_ERR_REQ_INVALID_VALIDATION_INVOCATION"></a>
280331

281-
Invalid validation invocation. Missing validation function for
332+
Invalid validation invocation. Missing validation function for
282333
HTTP part nor schema provided.
283334

284335
#### FST_ERR_SCH_MISSING_ID
@@ -306,6 +357,11 @@ The JSON schema provided for validation to a route is not valid.
306357

307358
The JSON schema provided for serialization of a route response is not valid.
308359

360+
#### FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX
361+
<a id="FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX"></a>
362+
363+
Response schemas should be nested under a valid status code (2XX).
364+
309365
#### FST_ERR_HTTP2_INVALID_VERSION
310366
<a id="FST_ERR_HTTP2_INVALID_VERSION"></a>
311367

@@ -319,7 +375,7 @@ Invalid initialization options.
319375
#### FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE
320376
<a id="FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE"></a>
321377

322-
Cannot set forceCloseConnections to `idle` as your HTTP server
378+
Cannot set forceCloseConnections to `idle` as your HTTP server
323379
does not support `closeIdleConnections` method.
324380

325381
<a name="FST_ERR_DUPLICATED_ROUTE"></a>
@@ -347,6 +403,46 @@ The `defaultRoute` type should be a function.
347403

348404
URL must be a string.
349405

406+
#### FST_ERR_ROUTE_OPTIONS_NOT_OBJ
407+
<a id="FST_ERR_ROUTE_OPTIONS_NOT_OBJ"></a>
408+
409+
Options for the route must be an object.
410+
411+
#### FST_ERR_ROUTE_DUPLICATED_HANDLER
412+
<a id="FST_ERR_ROUTE_DUPLICATED_HANDLER"></a>
413+
414+
Duplicate handler for the route is not allowed.
415+
416+
#### FST_ERR_ROUTE_HANDLER_NOT_FN
417+
<a id="FST_ERR_ROUTE_HANDLER_NOT_FN"></a>
418+
419+
Handler for the route must be a function.
420+
421+
#### FST_ERR_ROUTE_MISSING_HANDLER
422+
<a id="FST_ERR_ROUTE_MISSING_HANDLER"></a>
423+
424+
Missing handler function for the route.
425+
426+
#### FST_ERR_ROUTE_METHOD_NOT_SUPPORTED
427+
<a id="FST_ERR_ROUTE_METHOD_NOT_SUPPORTED"></a>
428+
429+
Method is not supported for the route.
430+
431+
#### FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED
432+
<a id="FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED"></a>
433+
434+
Body validation schema route is not supported.
435+
436+
#### FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT
437+
<a id="FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT"></a>
438+
439+
BodyLimit option must be an integer.
440+
441+
#### FST_ERR_ROUTE_REWRITE_NOT_STR
442+
<a id="FST_ERR_ROUTE_REWRITE_NOT_STR"></a>
443+
444+
Rewrite url needs to be of type "string".
445+
350446
#### FST_ERR_REOPENED_CLOSE_SERVER
351447
<a id="FST_ERR_REOPENED_CLOSE_SERVER"></a>
352448

@@ -363,26 +459,37 @@ Fastify is already listening.
363459
Installed Fastify plugin mismatched expected version.
364460

365461
<a name="FST_ERR_PLUGIN_CALLBACK_NOT_FN"></a>
462+
366463
#### FST_ERR_PLUGIN_CALLBACK_NOT_FN
367464

368465
Callback for a hook is not a function (mapped directly from `avvio`)
369466

370467
<a name="FST_ERR_PLUGIN_NOT_VALID"></a>
468+
371469
#### FST_ERR_PLUGIN_NOT_VALID
372470

373471
Plugin must be a function or a promise.
374472

375473
<a name="FST_ERR_ROOT_PLG_BOOTED"></a>
474+
376475
#### FST_ERR_ROOT_PLG_BOOTED
377476

378477
Root plugin has already booted (mapped directly from `avvio`)
379478

380479
<a name="FST_ERR_PARENT_PLUGIN_BOOTED"></a>
480+
381481
#### FST_ERR_PARENT_PLUGIN_BOOTED
382482

383483
Impossible to load plugin because the parent (mapped directly from `avvio`)
384484

385485
<a name="FST_ERR_PLUGIN_TIMEOUT"></a>
486+
386487
#### FST_ERR_PLUGIN_TIMEOUT
387488

388489
Plugin did not start in time. Default timeout (in millis): `10000`
490+
491+
<a name="FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE"></a>
492+
493+
#### FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE
494+
495+
The decorator is not present in the instance.

fastify.js

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,17 @@ const { defaultInitOptions } = getSecuredInitialConfig
5959
const {
6060
FST_ERR_ASYNC_CONSTRAINT,
6161
FST_ERR_BAD_URL,
62-
FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE
62+
FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE,
63+
FST_ERR_OPTIONS_NOT_OBJ,
64+
FST_ERR_QSP_NOT_FN,
65+
FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN,
66+
FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ,
67+
FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR,
68+
FST_ERR_VERSION_CONSTRAINT_NOT_STR,
69+
FST_ERR_INSTANCE_ALREADY_LISTENING,
70+
FST_ERR_REOPENED_CLOSE_SERVER,
71+
FST_ERR_ROUTE_REWRITE_NOT_STR,
72+
FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN
6373
} = errorCodes
6474

6575
const { buildErrorHandler } = require('./lib/error-handler.js')
@@ -90,15 +100,15 @@ function fastify (options) {
90100
options = options || {}
91101

92102
if (typeof options !== 'object') {
93-
throw new TypeError('Options must be an object')
103+
throw new FST_ERR_OPTIONS_NOT_OBJ()
94104
}
95105

96106
if (options.querystringParser && typeof options.querystringParser !== 'function') {
97-
throw new Error(`querystringParser option should be a function, instead got '${typeof options.querystringParser}'`)
107+
throw new FST_ERR_QSP_NOT_FN(typeof options.querystringParser)
98108
}
99109

100110
if (options.schemaController && options.schemaController.bucket && typeof options.schemaController.bucket !== 'function') {
101-
throw new Error(`schemaController.bucket option should be a function, instead got '${typeof options.schemaController.bucket}'`)
111+
throw new FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN(typeof options.schemaController.bucket)
102112
}
103113

104114
validateBodyLimitOption(options.bodyLimit)
@@ -117,10 +127,10 @@ function fastify (options) {
117127

118128
// Ajv options
119129
if (!ajvOptions.customOptions || Object.prototype.toString.call(ajvOptions.customOptions) !== '[object Object]') {
120-
throw new Error(`ajv.customOptions option should be an object, instead got '${typeof ajvOptions.customOptions}'`)
130+
throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ(typeof ajvOptions.customOptions)
121131
}
122132
if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) {
123-
throw new Error(`ajv.plugins option should be an array, instead got '${typeof ajvOptions.plugins}'`)
133+
throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins)
124134
}
125135

126136
// Instance Fastify components
@@ -156,7 +166,7 @@ function fastify (options) {
156166
deriveConstraint: options.versioning.deriveVersion,
157167
validate (value) {
158168
if (typeof value !== 'string') {
159-
throw new Error('Version constraint should be a string.')
169+
throw new FST_ERR_VERSION_CONSTRAINT_NOT_STR()
160170
}
161171
}
162172
}
@@ -463,7 +473,7 @@ function fastify (options) {
463473
return fastify
464474

465475
function throwIfAlreadyStarted (msg) {
466-
if (fastify[kState].started) throw new Error(msg)
476+
if (fastify[kState].started) throw new FST_ERR_INSTANCE_ALREADY_LISTENING(msg)
467477
}
468478

469479
// HTTP injection handling
@@ -479,7 +489,7 @@ function fastify (options) {
479489
if (fastify[kState].started) {
480490
if (fastify[kState].closing) {
481491
// Force to return an error
482-
const error = new Error('Server is closed')
492+
const error = new FST_ERR_REOPENED_CLOSE_SERVER()
483493
if (cb) {
484494
cb(error)
485495
return
@@ -564,7 +574,7 @@ function fastify (options) {
564574

565575
// wrapper that we expose to the user for hooks handling
566576
function addHook (name, fn) {
567-
throwIfAlreadyStarted('Cannot call "addHook" when fastify instance is already started!')
577+
throwIfAlreadyStarted('Cannot call "addHook"!')
568578

569579
if (fn == null) {
570580
throw new errorCodes.FST_ERR_HOOK_INVALID_HANDLER(name, fn)
@@ -607,7 +617,7 @@ function fastify (options) {
607617

608618
// wrapper that we expose to the user for schemas handling
609619
function addSchema (schema) {
610-
throwIfAlreadyStarted('Cannot call "addSchema" when fastify instance is already started!')
620+
throwIfAlreadyStarted('Cannot call "addSchema"!')
611621
this[kSchemaController].add(schema)
612622
this[kChildren].forEach(child => child.addSchema(schema))
613623
return this
@@ -697,33 +707,33 @@ function fastify (options) {
697707
}
698708

699709
function setNotFoundHandler (opts, handler) {
700-
throwIfAlreadyStarted('Cannot call "setNotFoundHandler" when fastify instance is already started!')
710+
throwIfAlreadyStarted('Cannot call "setNotFoundHandler"!')
701711

702712
fourOhFour.setNotFoundHandler.call(this, opts, handler, avvio, router.routeHandler)
703713
return this
704714
}
705715

706716
function setValidatorCompiler (validatorCompiler) {
707-
throwIfAlreadyStarted('Cannot call "setValidatorCompiler" when fastify instance is already started!')
717+
throwIfAlreadyStarted('Cannot call "setValidatorCompiler"!')
708718
this[kSchemaController].setValidatorCompiler(validatorCompiler)
709719
return this
710720
}
711721

712722
function setSchemaErrorFormatter (errorFormatter) {
713-
throwIfAlreadyStarted('Cannot call "setSchemaErrorFormatter" when fastify instance is already started!')
723+
throwIfAlreadyStarted('Cannot call "setSchemaErrorFormatter"!')
714724
validateSchemaErrorFormatter(errorFormatter)
715725
this[kSchemaErrorFormatter] = errorFormatter.bind(this)
716726
return this
717727
}
718728

719729
function setSerializerCompiler (serializerCompiler) {
720-
throwIfAlreadyStarted('Cannot call "setSerializerCompiler" when fastify instance is already started!')
730+
throwIfAlreadyStarted('Cannot call "setSerializerCompiler"!')
721731
this[kSchemaController].setSerializerCompiler(serializerCompiler)
722732
return this
723733
}
724734

725735
function setSchemaController (schemaControllerOpts) {
726-
throwIfAlreadyStarted('Cannot call "setSchemaController" when fastify instance is already started!')
736+
throwIfAlreadyStarted('Cannot call "setSchemaController"!')
727737
const old = this[kSchemaController]
728738
const schemaController = SchemaController.buildSchemaController(old, Object.assign({}, old.opts, schemaControllerOpts))
729739
this[kSchemaController] = schemaController
@@ -733,15 +743,15 @@ function fastify (options) {
733743
}
734744

735745
function setReplySerializer (replySerializer) {
736-
throwIfAlreadyStarted('Cannot call "setReplySerializer" when fastify instance is already started!')
746+
throwIfAlreadyStarted('Cannot call "setReplySerializer"!')
737747

738748
this[kReplySerializerDefault] = replySerializer
739749
return this
740750
}
741751

742752
// wrapper that we expose to the user for configure the custom error handler
743753
function setErrorHandler (func) {
744-
throwIfAlreadyStarted('Cannot call "setErrorHandler" when fastify instance is already started!')
754+
throwIfAlreadyStarted('Cannot call "setErrorHandler"!')
745755

746756
this[kErrorHandler] = buildErrorHandler(this[kErrorHandler], func.bind(this))
747757
return this
@@ -766,7 +776,8 @@ function fastify (options) {
766776
if (typeof url === 'string') {
767777
req.url = url
768778
} else {
769-
req.destroy(new Error(`Rewrite url for "${req.url}" needs to be of type "string" but received "${typeof url}"`))
779+
const err = new FST_ERR_ROUTE_REWRITE_NOT_STR(req.url, typeof url)
780+
req.destroy(err)
770781
}
771782
}
772783
}
@@ -779,9 +790,9 @@ fastify.errorCodes = errorCodes
779790

780791
function validateSchemaErrorFormatter (schemaErrorFormatter) {
781792
if (typeof schemaErrorFormatter !== 'function') {
782-
throw new Error(`schemaErrorFormatter option should be a function, instead got ${typeof schemaErrorFormatter}`)
793+
throw new FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN(typeof schemaErrorFormatter)
783794
} else if (schemaErrorFormatter.constructor.name === 'AsyncFunction') {
784-
throw new Error('schemaErrorFormatter option should not be an async function')
795+
throw new FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN('AsyncFunction')
785796
}
786797
}
787798

0 commit comments

Comments
 (0)