Vapor 3 - 搜索失败时返回不同的未来?

Vapor 3 - Returning a different Future when a search fails?

我正在使用 Vapor 3 并链接到 FoundationDB 数据库,所以我没有使用 Fluent。我有一个搜索记录的方法,但如果它没有 return 一条记录(因为我强制解包值),它显然会崩溃。

我想保护数据库的读取,return 如果没有找到记录则响应。然而,这将不是未来预期的记录。我在想我应该 return 不同的回应,但我不确定如何改变预期的结果。

//creates a specific country
func getCountry( req: Request) throws -> Future<Country> {
    // get Country name from get parameter string
    let countryString = try req.parameters.next(String.self)


    // get record from Database. This could fail and so needs to be guarded. What response should be returned as the Future requires a Country datatype?

       let record =  FDBConnector().getRecord(path: Subspace("iVendor").subspace(["Countries", countryString]))



    let newCountry = try JSONDecoder().decode(Country.self, from: record!)
    // return Country Struct
    return Future.map(on: req) {return newCountry }

}

这里有几个选项。

首先,如果您从方法中抛出错误:

guard let record =  FDBConnector().getRecord(path: Subspace("iVendor").subspace(["Countries", countryString])) else {
    throw Abort(.notFound, reason: "No country found with name \(countryString)")
}

错误将转换为 404(未找到)响应,错误消息为 "No country found with name \(countryString)"

如果您想更好地控制结果响应,可以将路由处理程序的 return 类型更改为 Future<Response>。然后,您可以将 Country 对象编码为响应或创建自定义错误响应。不过,此方法确实需要一些额外的工作。

let response = Response(using: req)
guard let record =  FDBConnector().getRecord(path: Subspace("iVendor").subspace(["Countries", countryString])) else {
    try response.content.encode(["message": "Country not found"])
    response.http.status = .notFound
    return response
}

try response.content.encode(record)
return response

请注意,如果您希望该代码段有效,您必须使 Country 符合 Content