Skip to main content

生命周期

生命周期

¥Lifecycle

遵循 Fastify 内部生命周期的架构。

¥Following the schema of the internal lifecycle of Fastify.

每个部分的右侧分支都有生命周期的下一阶段,左侧分支有相应的错误代码,如果父级抛出错误,则会生成相应的错误代码(请注意,所有错误都会由 Fastify 自动处理)。

¥On the right branch of every section there is the next phase of the lifecycle, on the left branch there is the corresponding error code that will be generated if the parent throws an error (note that all the errors are automatically handled by Fastify).

Incoming Request

└─▶ Routing

└─▶ Instance Logger

4**/5** ◀─┴─▶ onRequest Hook

4**/5** ◀─┴─▶ preParsing Hook

4**/5** ◀─┴─▶ Parsing

4**/5** ◀─┴─▶ preValidation Hook

400 ◀─┴─▶ Validation

4**/5** ◀─┴─▶ preHandler Hook

4**/5** ◀─┴─▶ User Handler

└─▶ Reply

4**/5** ◀─┴─▶ preSerialization Hook

└─▶ onSend Hook

4**/5** ◀─┴─▶ Outgoing Response

└─▶ onResponse Hook

User Handler 之前或期间的任何时候,都可以调用 reply.hijack() 来防止 Fastify:

¥At any point before or during the User Handler, reply.hijack() can be called to prevent Fastify from:

  • 运行以下所有钩子和用户处理程序

    ¥Running all the following hooks and user handler

  • 自动发送响应

    ¥Sending the response automatically

NB (*):如果使用 reply.raw 将响应发送回用户,则仍将执行 onResponse 钩子

¥NB (*): If reply.raw is used to send a response back to the user, onResponse hooks will still be executed

Reply 生命周期

¥Reply Lifecycle

每当用户处理请求时,结果可能是:

¥Whenever the user handles the request, the result may be:

  • 在异步处理程序中:它返回一个有效负载

    ¥in async handler: it returns a payload

  • 在异步处理程序中:它抛出了 Error

    ¥in async handler: it throws an Error

  • 在同步处理程序中:它发送一个有效负载

    ¥in sync handler: it sends a payload

  • 在同步处理程序中:它发送一个 Error 实例

    ¥in sync handler: it sends an Error instance

如果响应被劫持,我们将跳过以下所有步骤。否则,在提交时,执行的数据流程如下:

¥If the reply was hijacked, we skip all the below steps. Otherwise, when it is being submitted, the data flow performed is the following:

                        ★ schema validation Error

└─▶ schemaErrorFormatter

reply sent ◀── JSON ─┴─ Error instance

│ ★ throw an Error
★ send or return │ │
│ │ │
│ ▼ │
reply sent ◀── JSON ─┴─ Error instance ──▶ setErrorHandler ◀─────┘

reply sent ◀── JSON ─┴─ Error instance ──▶ onError Hook

└─▶ reply sent

注意:reply sent 表示 JSON 有效负载将通过以下方式序列化:

¥Note: reply sent means that the JSON payload will be serialized by: