Skip to main content

错误

错误

¥Errors

目录

¥Table of contents

Node.js 中的错误处理

¥Error Handling In Node.js

未捕获的错误

¥Uncaught Errors

在 Node.js 中,未捕获的错误可能导致内存泄漏、文件描述符泄漏和其他主要生产问题。Domains 是修复此问题的失败尝试。

¥In Node.js, uncaught errors can cause memory leaks, file descriptor leaks, and other major production issues. Domains were a failed attempt to fix this.

鉴于不可能合理地处理所有未捕获的错误,处理它们的最佳方法是 crash

¥Given that it is not possible to process all uncaught errors sensibly, the best way to deal with them is to crash.

捕获 Promise 中的错误

¥Catching Errors In Promises

使用 promise 时,同步附加 .catch() 处理程序。

¥When using promises, attach a .catch() handler synchronously.

Fastify 中的错误

¥Errors In Fastify

Fastify 遵循全有或全无的方法,旨在精简和优化。开发者负责确保错误得到正确处理。

¥Fastify follows an all-or-nothing approach and aims to be lean and optimal. The developer is responsible for ensuring errors are handled properly.

输入数据错误

¥Errors In Input Data

大多数错误是由意外的输入数据引起的,因此建议使用 根据 JSON 模式验证输入数据

¥Most errors result from unexpected input data, so it is recommended to validate input data against a JSON schema.

在 Fastify 中捕获未捕获的错误

¥Catching Uncaught Errors In Fastify

Fastify 尝试在不影响性能的情况下捕获尽可能多的未捕获错误。这包括:

¥Fastify tries to catch as many uncaught errors as possible without hindering performance. This includes:

  1. 同步路由,例如 app.get('/', () => { throw new Error('kaboom') })

    ¥synchronous routes, e.g. app.get('/', () => { throw new Error('kaboom') })

  2. async 路由,例如 app.get('/', async () => { throw new Error('kaboom') })

    ¥async routes, e.g. app.get('/', async () => { throw new Error('kaboom') })

在这两种情况下,错误都将被安全捕获并路由到 Fastify 的默认错误处理程序,从而产生通用的 500 Internal Server Error 响应。

¥In both cases, the error will be caught safely and routed to Fastify's default error handler, resulting in a generic 500 Internal Server Error response.

要自定义此行为,请使用 setErrorHandler

¥To customize this behavior, use setErrorHandler.

Fastify 生命周期钩子和自定义错误处理程序中的错误

¥Errors In Fastify Lifecycle Hooks And A Custom Error Handler

钩子文档

¥From the Hooks documentation:

如果在执行钩子时出现错误,只需将其传递给 done(),Fastify 就会自动关闭请求并向用户发送相应的错误代码。

¥If you get an error during the execution of your hook, just pass it to done() and Fastify will automatically close the request and send the appropriate error code to the user.

当通过 setErrorHandler 定义自定义错误处理程序时,它将接收传递给 done() 回调或通过其他受支持的自动错误处理机制的错误。如果多次使用 setErrorHandler,则错误将被路由到错误 封装上下文 中最先的处理程序。错误处理程序是完全封装的,因此插件内的 setErrorHandler 调用将限制错误处理程序到该插件的上下文。

¥When a custom error handler is defined through setErrorHandler, it will receive the error passed to the done() callback or through other supported automatic error handling mechanisms. If setErrorHandler is used multiple times, the error will be routed to the most precedent handler within the error encapsulation context. Error handlers are fully encapsulated, so a setErrorHandler call within a plugin will limit the error handler to that plugin's context.

根错误处理程序是 Fastify 的通用错误处理程序。如果存在,此错误处理程序将使用 Error 对象中的标头和状态代码。如果提供了自定义错误处理程序,则不会自动设置标头和状态代码。

¥The root error handler is Fastify's generic error handler. This error handler will use the headers and status code in the Error object, if they exist. The headers and status code will not be automatically set if a custom error handler is provided.

使用自定义错误处理程序时应考虑以下事项:

¥The following should be considered when using a custom error handler:

  • reply.send(data) 的行为与 常规路由处理程序 相同

    ¥reply.send(data) behaves as in regular route handlers

    • 对象被序列化,如果定义则触发 preSerialization 生命周期钩子

      ¥objects are serialized, triggering the preSerialization lifecycle hook if defined

    • 字符串、缓冲区和流将使用适当的标头发送到客户端(无序列化)

      ¥strings, buffers, and streams are sent to the client with appropriate headers (no serialization)

  • 在自定义错误处理程序中抛出新错误将调用父 errorHandler

    ¥Throwing a new error in a custom error handler will call the parent errorHandler.

    • onError 钩子将针对第一个抛出的错误触发一次

      ¥The onError hook will be triggered once for the first error thrown

    • 生命周期钩子不会两次触发错误。Fastify 内部监控错误调用,以避免在生命周期的回复阶段(路由处理程序之后的阶段)抛出错误而导致无限循环

      ¥An error will not be triggered twice from a lifecycle hook. Fastify internally monitors error invocation to avoid infinite loops for errors thrown in the reply phases of the lifecycle (those after the route handler)

当通过 setErrorHandler 使用 Fastify 的自定义错误处理时,请注意错误如何在自定义和默认错误处理程序之间传播。

¥When using Fastify's custom error handling through setErrorHandler, be aware of how errors are propagated between custom and default error handlers.

如果插件的错误处理程序重新抛出不是 错误 实例的错误,则它不会传播到父上下文错误处理程序。相反,它将被默认错误处理程序捕获。这可以在以下示例的 /bad 路由中看到。

¥If a plugin's error handler re-throws an error that is not an instance of Error, it will not propagate to the parent context error handler. Instead, it will be caught by the default error handler. This can be seen in the /bad route of the example below.

为确保一致的错误处理,请抛出 Error 的实例。例如,在 /bad 路由中将 throw 'foo' 替换为 throw new Error('foo'),以确保错误按预期通过自定义错误处理链传播。这种做法有助于避免在 Fastify 中使用自定义错误处理时出现的潜在陷阱。

¥To ensure consistent error handling, throw instances of Error. For example, replace throw 'foo' with throw new Error('foo') in the /bad route to ensure errors propagate through the custom error handling chain as intended. This practice helps avoid potential pitfalls when working with custom error handling in Fastify.

例如:

¥For example:

const Fastify = require('fastify')

// Instantiate the framework
const fastify = Fastify({
logger: true
})

// Register parent error handler
fastify.setErrorHandler((error, request, reply) => {
reply.status(500).send({ ok: false })
})

fastify.register((app, options, next) => {
// Register child error handler
fastify.setErrorHandler((error, request, reply) => {
throw error
})

fastify.get('/bad', async () => {
// Throws a non-Error type, 'bar'
throw 'foo'
})

fastify.get('/good', async () => {
// Throws an Error instance, 'bar'
throw new Error('bar')
})

next()
})

// Run the server
fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
// Server is listening at ${address}
})

Fastify 错误代码

¥Fastify Error Codes

你可以访问 errorCodes 进行映射:

¥You can access errorCodes for mapping:

// ESM
import { errorCodes } from 'fastify'

// CommonJS
const errorCodes = require('fastify').errorCodes

例如:

¥For example:

const Fastify = require('fastify')

// Instantiate the framework
const fastify = Fastify({
logger: true
})

// Declare a route
fastify.get('/', function (request, reply) {
reply.code('bad status code').send({ hello: 'world' })
})

fastify.setErrorHandler(function (error, request, reply) {
if (error instanceof Fastify.errorCodes.FST_ERR_BAD_STATUS_CODE) {
// Log error
this.log.error(error)
// Send error response
reply.status(500).send({ ok: false })
} else {
// Fastify will use parent error handler to handle this
reply.send(error)
}
})

// Run the server!
fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
// Server is now listening on ${address}
})

下面是包含 Fastify 使用的所有错误代码的表格。

¥Below is a table with all the error codes used by Fastify.

CodeDescriptionHow to solveDiscussion
FST_ERR_NOT_FOUND404 Not Found-#1168
FST_ERR_OPTIONS_NOT_OBJFastify options wrongly specified.Fastify options should be an object.#4554
FST_ERR_QSP_NOT_FNQueryStringParser wrongly specified.QueryStringParser option should be a function.#4554
FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FNSchemaController.bucket wrongly specified.SchemaController.bucket option should be a function.#4554
FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FNSchemaErrorFormatter option wrongly specified.SchemaErrorFormatter option should be a non async function.#4554
FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJajv.customOptions wrongly specified.ajv.customOptions option should be an object.#4554
FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARRajv.plugins option wrongly specified.ajv.plugins option should be an array.#4554
FST_ERR_CTP_ALREADY_PRESENTThe parser for this content type was already registered.Use a different content type or delete the already registered parser.#1168
FST_ERR_CTP_INVALID_TYPEContent-Type wrongly specifiedThe Content-Type should be a string.#1168
FST_ERR_CTP_EMPTY_TYPEContent-Type is an empty string.Content-Type cannot be an empty string.#1168
FST_ERR_CTP_INVALID_HANDLERInvalid handler for the content type.Use a different handler.#1168
FST_ERR_CTP_INVALID_PARSE_TYPEThe provided parse type is not supported.Accepted values are string or buffer.#1168
FST_ERR_CTP_BODY_TOO_LARGEThe request body is larger than the provided limit.Increase the limit in the Fastify server instance setting: bodyLimit#1168
FST_ERR_CTP_INVALID_MEDIA_TYPEThe received media type is not supported (i.e. there is no suitable Content-Type parser for it).Use a different content type.#1168
FST_ERR_CTP_INVALID_CONTENT_LENGTHRequest body size did not match Content-Length.Check the request body size and the Content-Length header.#1168
FST_ERR_CTP_EMPTY_JSON_BODYBody cannot be empty when content-type is set to application/json.Check the request body.#1253
FST_ERR_CTP_INSTANCE_ALREADY_STARTEDFastify is already started.-#4554
FST_ERR_INSTANCE_ALREADY_LISTENINGFastify instance is already listening.-#4554
FST_ERR_DEC_ALREADY_PRESENTA decorator with the same name is already registered.Use a different decorator name.#1168
FST_ERR_DEC_DEPENDENCY_INVALID_TYPEThe dependencies of decorator must be of type Array.Use an array for the dependencies.#3090
FST_ERR_DEC_MISSING_DEPENDENCYThe decorator cannot be registered due to a missing dependency.Register the missing dependency.#1168
FST_ERR_DEC_AFTER_STARTThe decorator cannot be added after start.Add the decorator before starting the server.#2128
FST_ERR_DEC_REFERENCE_TYPEThe decorator cannot be a reference type.Define the decorator with a getter/setter interface or an empty decorator with a hook.#5462
FST_ERR_DEC_UNDECLAREDAn attempt was made to access a decorator that has not been declared.Declare the decorator before using it.#
FST_ERR_HOOK_INVALID_TYPEThe hook name must be a string.Use a string for the hook name.#1168
FST_ERR_HOOK_INVALID_HANDLERThe hook callback must be a function.Use a function for the hook callback.#1168
FST_ERR_HOOK_INVALID_ASYNC_HANDLERAsync function has too many arguments. Async hooks should not use the done argument.Remove the done argument from the async hook.#4367
FST_ERR_HOOK_NOT_SUPPORTEDThe hook is not supported.Use a supported hook.#4554
FST_ERR_MISSING_MIDDLEWAREYou must register a plugin for handling middlewares, visit Middleware for more info.Register a plugin for handling middlewares.#2014
FST_ERR_HOOK_TIMEOUTA callback for a hook timed out.Increase the timeout for the hook.#3106
FST_ERR_LOG_INVALID_DESTINATIONThe logger does not accept the specified destination.Use a 'stream' or a 'file' as the destination.#1168
FST_ERR_LOG_INVALID_LOGGERThe logger should have all these methods: 'info', 'error', 'debug', 'fatal', 'warn', 'trace', 'child'.Use a logger with all the required methods.#4520
FST_ERR_LOG_INVALID_LOGGER_INSTANCEThe loggerInstance only accepts a logger instance, not a configuration object.To pass a configuration object, use 'logger' instead.#5020
FST_ERR_LOG_INVALID_LOGGER_CONFIGThe logger option only accepts a configuration object, not a logger instance.To pass an instance, use 'loggerInstance' instead.#5020
FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDEDYou cannot provide both 'logger' and 'loggerInstance'.Please provide only one option.#5020
FST_ERR_REP_INVALID_PAYLOAD_TYPEReply payload can be either a string or a Buffer.Use a string or a Buffer for the payload.#1168
FST_ERR_REP_RESPONSE_BODY_CONSUMEDUsing Response as reply payload, but the body is being consumed.Make sure you don't consume the Response.body#5286
FST_ERR_REP_READABLE_STREAM_LOCKEDUsing ReadableStream as reply payload, but locked with another reader.Make sure you don't call the Readable.getReader before sending or release lock with reader.releaseLock() before sending.#5920
FST_ERR_REP_ALREADY_SENTA response was already sent.-#1336
FST_ERR_REP_SENT_VALUEThe only possible value for reply.sent is true.-#1336
FST_ERR_SEND_INSIDE_ONERRYou cannot use send inside the onError hook.-#1348
FST_ERR_SEND_UNDEFINED_ERRUndefined error has occurred.-#2074
FST_ERR_BAD_STATUS_CODEThe status code is not valid.Use a valid status code.#2082
FST_ERR_BAD_TRAILER_NAMECalled reply.trailer with an invalid header name.Use a valid header name.#3794
FST_ERR_BAD_TRAILER_VALUECalled reply.trailer with an invalid type. Expected a function.Use a function.#3794
FST_ERR_FAILED_ERROR_SERIALIZATIONFailed to serialize an error.-#4601
FST_ERR_MISSING_SERIALIZATION_FNMissing serialization function.Add a serialization function.#3970
FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FNMissing Content-Type serialization function.Add a serialization function.#4264
FST_ERR_REQ_INVALID_VALIDATION_INVOCATIONInvalid validation invocation. Missing validation function for HTTP part nor schema provided.Add a validation function.#3970
FST_ERR_SCH_MISSING_IDThe schema provided does not have $id property.Add a $id property.#1168
FST_ERR_SCH_ALREADY_PRESENTA schema with the same $id already exists.Use a different $id.#1168
FST_ERR_SCH_CONTENT_MISSING_SCHEMAA schema is missing for the corresponding content type.Add a schema.#4264
FST_ERR_SCH_DUPLICATESchema with the same attribute already present!Use a different attribute.#1954
FST_ERR_SCH_VALIDATION_BUILDThe JSON schema provided for validation to a route is not valid.Fix the JSON schema.#2023
FST_ERR_SCH_SERIALIZATION_BUILDThe JSON schema provided for serialization of a route response is not valid.Fix the JSON schema.#2023
FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XXResponse schemas should be nested under a valid status code (2XX).Use a valid status code.#4554
FST_ERR_HTTP2_INVALID_VERSIONHTTP2 is available only from node >= 8.8.1.Use a higher version of node.#1346
FST_ERR_INIT_OPTS_INVALIDInvalid initialization options.Use valid initialization options.#1471
FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLECannot set forceCloseConnections to idle as your HTTP server does not support closeIdleConnections method.Use a different value for forceCloseConnections.#3925
FST_ERR_DUPLICATED_ROUTEThe HTTP method already has a registered controller for that URL.Use a different URL or register the controller for another HTTP method.#2954
FST_ERR_BAD_URLThe router received an invalid URL.Use a valid URL.#2106
FST_ERR_ASYNC_CONSTRAINTThe router received an error when using asynchronous constraints.-#4323
FST_ERR_INVALID_URLURL must be a string.Use a string for the URL.#3653
FST_ERR_ROUTE_OPTIONS_NOT_OBJOptions for the route must be an object.Use an object for the route options.#4554
FST_ERR_ROUTE_DUPLICATED_HANDLERDuplicate handler for the route is not allowed.Use a different handler.#4554
FST_ERR_ROUTE_HANDLER_NOT_FNHandler for the route must be a function.Use a function for the handler.#4554
FST_ERR_ROUTE_MISSING_HANDLERMissing handler function for the route.Add a handler function.#4554
FST_ERR_ROUTE_METHOD_INVALIDMethod is not a valid value.Use a valid value for the method.#4750
FST_ERR_ROUTE_METHOD_NOT_SUPPORTEDMethod is not supported for the route.Use a supported method.#4554
FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTEDBody validation schema route is not supported.Use a different different method for the route.#4554
FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INTbodyLimit option must be an integer.Use an integer for the bodyLimit option.#4554
FST_ERR_ROUTE_REWRITE_NOT_STRrewriteUrl needs to be of type string.Use a string for the rewriteUrl.#4554
FST_ERR_REOPENED_CLOSE_SERVERFastify has already been closed and cannot be reopened.-#2415
FST_ERR_REOPENED_SERVERFastify is already listening.-#2415
FST_ERR_PLUGIN_VERSION_MISMATCHInstalled Fastify plugin mismatched expected version.Use a compatible version of the plugin.#2549
FST_ERR_PLUGIN_CALLBACK_NOT_FNCallback for a hook is not a function.Use a function for the callback.#3106
FST_ERR_PLUGIN_NOT_VALIDPlugin must be a function or a promise.Use a function or a promise for the plugin.#3106
FST_ERR_ROOT_PLG_BOOTEDRoot plugin has already booted.-#3106
FST_ERR_PARENT_PLUGIN_BOOTEDImpossible to load plugin because the parent (mapped directly from avvio)-#3106
FST_ERR_PLUGIN_TIMEOUTPlugin did not start in time.Increase the timeout for the plugin.#3106
FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCEThe decorator is not present in the instance.-#4554
FST_ERR_PLUGIN_INVALID_ASYNC_HANDLERThe plugin being registered mixes async and callback styles.-#5141
FST_ERR_VALIDATIONThe Request failed the payload validation.Check the request payload.#4824
FST_ERR_LISTEN_OPTIONS_INVALIDInvalid listen options.Check the listen options.#4886
FST_ERR_ERROR_HANDLER_NOT_FNError Handler must be a functionProvide a function to setErrorHandler.#5317