Vert.x Web多状态码错误处理器实现方案问询
Vert.x Web 批量绑定多状态码错误处理器 & 405错误捕获问题解决
先解决405错误未被捕获的问题
Vert.x默认不会主动触发"方法不允许"的错误处理流程,必须先开启全局配置:
router.options.setHandleMethodNotAllowed(true)
开启后,当请求路径匹配但HTTP方法不被支持时,才会抛出405错误并进入错误处理链路。
实现批量绑定多状态码到同一错误处理器
利用Kotlin的扩展函数,给Router类添加批量绑定方法,完全满足你期望的调用方式:
fun Router.errorHandler(vararg statusCodes: Int, handler: (RoutingContext) -> Unit) { statusCodes.forEach { code -> this.errorHandler(code, handler) } }
通过这个扩展,就能一次性给多个状态码绑定同一个处理逻辑。
完整示例代码
import io.vertx.core.Vertx import io.vertx.core.http.HttpMethod import io.vertx.ext.web.Router import io.vertx.ext.web.RoutingContext fun main() { val vertx = Vertx.vertx() val router: Router = Router.router(vertx) // 开启方法不允许的错误处理开关 router.options.setHandleMethodNotAllowed(true) // 自定义批量错误处理器扩展函数 fun Router.errorHandler(vararg statusCodes: Int, handler: (RoutingContext) -> Unit) { statusCodes.forEach { code -> this.errorHandler(code, handler) } } // 注册业务路由 router.route(HttpMethod.GET, "/test").handler { ctx -> ctx.response().end("GET /test 处理成功") } // 批量绑定404、405、406到同一错误处理器 router.errorHandler(404, 405, 406) { ctx -> val statusCode = ctx.statusCode() val customMsg = when(statusCode) { 404 -> "抱歉,你访问的资源不存在" 405 -> "抱歉,该资源不支持当前请求方法" 406 -> "抱歉,无法提供你要求的响应格式" else -> "请求处理失败" } ctx.response() .setStatusCode(statusCode) .putHeader("Content-Type", "application/json") .end("{\"code\": $statusCode, \"message\": \"$customMsg\"}") } vertx.createHttpServer().requestHandler(router).listen(8080) { if (it.succeeded()) { println("服务器启动在8080端口") } else { println("服务器启动失败: ${it.cause().message}") } } }
测试验证
- 访问
GET http://localhost:8080/test→ 返回正常业务响应 - 访问
GET http://localhost:8080/nonexist→ 触发404,返回自定义JSON响应 - 访问
POST http://localhost:8080/test→ 触发405,返回自定义JSON响应
内容的提问来源于stack exchange,提问作者Vencat
相关产品推荐
相关产品推荐

