Scala创建POST端点遇类型不兼容错误:ContextRequest与Request不匹配
问题修复方案
错误原因
你遇到的类型不兼容错误,是因为路由里的as _指令把请求对象从Request[F]包装成了ContextRequest[F, A],但你的handler.handle方法期望接收Request[F]类型,两者无法匹配。
as _是用来解析请求体并提取为指定类型的指令,而你当前的处理逻辑完全没用到请求体,这个指令属于多余的,直接移除就能解决类型不匹配问题。
修改后的代码
case _ @ POST -> Root / "batch-notify" => handler.handle("create.notifications.batchNotify") { for { _ <- log.info("Running batch notification job") *> Sync[F].pure(()) r <- batchingService.createNotifications.flatMap(_ => Ok()) } yield r }.fireAndForget.flatMap(_ => Accepted())
额外说明
如果后续需要处理这个POST请求的请求体(比如要解析成NotificationBatch类型),可以保留as指令并指定具体类型,同时确保handler.handle能接受对应的ContextRequest[F, 目标类型]:
// 示例:假设需要将请求体解析为NotificationBatch类型 case _ @ POST -> Root / "batch-notify" as batchData: NotificationBatch => handler.handle("create.notifications.batchNotify") { req: ContextRequest[F, NotificationBatch] => // 通过req.body可以获取解析后的请求体 for { _ <- log.info("Running batch notification job with request body") *> Sync[F].pure(()) r <- batchingService.createNotifications(batchData).flatMap(_ => Ok()) } yield r }.fireAndForget.flatMap(_ => Accepted())
内容的提问来源于stack exchange,提问作者Ahmed Wasim
相关产品推荐
相关产品推荐

