Skip to content

超时中间件

¥Timeout Middleware

Timeout 中间件使你能够轻松管理应用中的请求超时。它允许你设置请求的最大持续时间,并在超过指定超时时可选地定义自定义错误响应。

¥The Timeout Middleware enables you to easily manage request timeouts in your application. It allows you to set a maximum duration for requests and optionally define custom error responses if the specified timeout is exceeded.

导入

¥Import

ts
import { Hono } from 'hono'
import { timeout } from 'hono/timeout'

用法

¥Usage

以下是使用 Timeout Middleware 的默认和自定义设置的方法:

¥Here's how to use the Timeout Middleware with both default and custom settings:

默认设置:

¥Default Settings:

ts
const app = new Hono()

// Applying a 5-second timeout
app.use('/api', timeout(5000))

// Handling a route
app.get('/api/data', async (c) => {
  // Your route handler logic
  return c.json({ data: 'Your data here' })
})

自定义设置:

¥Custom settings:

ts
import { HTTPException } from 'hono/http-exception'

// Custom exception factory function
const customTimeoutException = (context) =>
  new HTTPException(408, {
    message: `Request timeout after waiting ${context.req.headers.get(
      'Duration'
    )} seconds. Please try again later.`,
  })

// for Static Exception Message
// const customTimeoutException = new HTTPException(408, {
//   message: 'Operation timed out. Please try again later.'
// });

// Applying a 1-minute timeout with a custom exception
app.use('/api/long-process', timeout(60000, customTimeoutException))

app.get('/api/long-process', async (c) => {
  // Simulate a long process
  await new Promise((resolve) => setTimeout(resolve, 61000))
  return c.json({ data: 'This usually takes longer' })
})

注释

¥Notes

  • 可以以毫秒为单位指定超时持续时间。如果超过指定的持续时间,中间件将自动拒绝 promise 并可能抛出错误。

    ¥The duration for the timeout can be specified in milliseconds. The middleware will automatically reject the promise and potentially throw an error if the specified duration is exceeded.

  • 超时中间件不能与流一起使用,因此,请同时使用 stream.closesetTimeout

    ¥The timeout middleware cannot be used with stream Thus, use stream.close and setTimeout together.

ts
app.get('/sse', async (c) => {
  let id = 0
  let running = true
  let timer: number | undefined

  return streamSSE(c, async (stream) => {
    timer = setTimeout(() => {
      console.log('Stream timeout reached, closing stream')
      stream.close()
    }, 3000) as unknown as number

    stream.onAbort(async () => {
      console.log('Client closed connection')
      running = false
      clearTimeout(timer)
    })

    while (running) {
      const message = `It is ${new Date().toISOString()}`
      await stream.writeSSE({
        data: message,
        event: 'time-update',
        id: String(id++),
      })
      await stream.sleep(1000)
    }
  })
})

中间件冲突

¥Middleware Conflicts

请注意中间件的顺序,特别是在使用错误处理或其他与时间相关的中间件时,因为它可能会影响此超时中间件的行为。

¥Be cautious about the order of middleware, especially when using error-handling or other timing-related middleware, as it might affect the behavior of this timeout middleware.

Hono v4.9 中文网 - 粤ICP备13048890号