Timeout 中间件
Timeout 中间件让你轻松管理应用的请求超时。可以设置请求的最长持续时间,并在超过指定时间时,选择定义自定义错误响应。
导入
ts
import { Hono } from 'hono'
import { timeout } from 'hono/timeout'用法
以下分别展示默认配置和自定义配置下的 Timeout 中间件用法:
默认配置:
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' })
})自定义配置:
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' })
})注意事项
超时时间可以以毫秒指定。超过指定时长后,中间件会自动拒绝 Promise,并可能抛出错误。
Timeout 中间件无法用于流,因此请结合使用
stream.close和setTimeout。
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)
}
})
})中间件冲突
请注意中间件的顺序,尤其是同时使用错误处理或其他与时间相关的中间件时,因为顺序可能影响 Timeout 中间件的行为。