You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Bun的Hono应用:如何处理参数不匹配正则的错误?

在Hono中处理路由参数正则不匹配的错误

当你用正则约束路由参数时,不符合规则的请求不会命中目标路由,默认会返回404。要实现自定义错误响应,你可以通过以下几种方式处理:

方案一:自定义全局404处理(快速统一)

利用Hono内置的notFound方法,针对/post/*/*格式的请求返回参数错误提示,其他404请求返回通用提示:

import { Hono } from 'hono'

const app = new Hono()

// 你的目标路由(带参数正则约束)
app.get('/post/:date{[0-9]+}/:title{[a-z]+}', (c) => {
  const { date, title } = c.req.param()
  return c.json({ status: 'success', data: { date, title } })
})

// 自定义404逻辑
app.notFound((c) => {
  const path = c.req.path
  // 判断请求路径是否符合/post/xxx/xxx格式但参数不合法
  if (/^\/post\/.+\/.+$/.test(path)) {
    return c.json(
      { error: '参数格式错误:date必须为纯数字,title必须为小写字母' },
      400 // 返回400状态码而非默认404
    )
  }
  // 其他无效路径的404提示
  return c.json({ error: '页面不存在' }, 404)
})

export default app

方案二:手动参数验证+全局错误捕获(精准提示)

先匹配宽泛的路由,在handler中手动验证参数格式,抛出错误后用onError钩子统一处理:

import { Hono } from 'hono'

const app = new Hono()

// 匹配所有/post/:date/:title格式的请求,不限制参数正则
app.get('/post/:date/:title', (c) => {
  const { date, title } = c.req.param()

  // 逐个验证参数
  if (!/^[0-9]+$/.test(date)) {
    throw new Error('date参数必须为纯数字')
  }
  if (!/^[a-z]+$/.test(title)) {
    throw new Error('title参数只能包含小写字母')
  }

  // 参数合法,执行业务逻辑
  return c.json({ status: 'success', data: { date, title } })
})

// 全局错误处理钩子
app.onError((err, c) => {
  // 判断是否为参数验证错误
  if (err.message.includes('参数')) {
    return c.json({ error: err.message }, 400)
  }
  // 其他服务器错误返回500
  return c.json({ error: '服务器内部错误' }, 500)
})

export default app

方案三:使用Validator中间件(优雅解耦)

借助Hono官方的@hono/validator中间件,将参数验证逻辑抽离,代码更简洁:

  1. 先安装依赖:
bun add @hono/validator
  1. 实现代码:
import { Hono } from 'hono'
import { validator } from '@hono/validator'

const app = new Hono()

app.get(
  '/post/:date/:title',
  // 验证路由参数
  validator('param', (params, c) => {
    const errors: string[] = []
    if (!/^[0-9]+$/.test(params.date)) {
      errors.push('date必须为纯数字')
    }
    if (!/^[a-z]+$/.test(params.title)) {
      errors.push('title只能包含小写字母')
    }
    // 验证失败直接返回错误响应
    if (errors.length > 0) {
      return c.json({ errors }, 400)
    }
    // 验证通过,将参数传递给下一个handler
    return params
  }),
  // 业务逻辑handler
  (c) => {
    const { date, title } = c.req.param()
    return c.json({ status: 'success', data: { date, title } })
  }
)

export default app

方案对比

  • 方案一:适合需要快速统一处理参数格式错误的场景,无需手动写验证逻辑,但无法区分具体是哪个参数出错。
  • 方案二:能返回精准的参数错误提示,但需要手动编写验证代码,耦合在handler中。
  • 方案三:代码结构更清晰,验证逻辑与业务逻辑解耦,推荐用于复杂的参数校验场景。

内容的提问来源于stack exchange,提问作者hantoren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 08:34:58