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

Swift Vapor:catchMap未被等待致错误未捕获的解决方法

Fixing Unhandled Errors in Vapor Email Delivery with Mailgun

Your issue boils down to nested futures not being flattened, which means errors from deliveryService.send never make it to your catchMap handler. Here's the breakdown:

When you use map on the render future, you’re returning another Future<Response> inside it. That turns your entire chain into a Future<Future<Response>> (a nested future). The outer catchMap only catches errors from the initial render call—any errors from send get trapped inside the inner future, which never gets properly awaited before the request returns.

The Fix: Use flatMap Instead of map

flatMap is built exactly for this scenario: it takes a future, runs an async operation that returns another future, and flattens the result into a single, linear future chain. This ensures all errors (from both render and send) flow through to your error handler.

Here's your corrected code:

return emailTemplate.render(emailData, on: req)
    .flatMap { message -> Future<Response> in 
        let deliveryService = try req.make(EmailDeliveryService.self)
        return try deliveryService.send(message, on: req)
    }
    .catchMap { error in 
        throw Abort(.internalServerError, reason: "Error sending email.")
    }
    .transform(to: savedObj)

Why This Works:

  1. Flattening the Future Chain: flatMap replaces the messy nested Future<Future<Response>> with a single Future<Response>, so every step in the async flow is part of one continuous chain.
  2. Full Error Propagation: Now, if either emailTemplate.render fails or deliveryService.send fails, the error will be passed straight to the catchMap handler. This triggers your Abort before the request completes, ensuring the client gets an internal server error instead of an incorrect success response.
  3. Sync Error Handling: Even the try req.make(...) call inside flatMap will be converted into a failed future if it throws, so that error is also caught by catchMap.

内容的提问来源于stack exchange,提问作者marked-down

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:25:35