Vapor swift 代码在本地主机上工作,但在 heroku 部署后所有 api 工作正常,但这个崩溃

Vapor swift Code working on localhost but after deploying at heroku all apis working fine but this one crashes

此函数在 api 命中时调用,看起来错误在第二个 do 块中的 return 语句中,它在本地主机上运行良好但在 heroku 上部署并命中此 api, 它说 无法将类型 'Vapor.Request' (0x55e629265b00) 的值转换为 'Swift.Error' (0x7fd61a06b560)。

我在 localhost 中曾经遇到过同样的错误,并使用 try 解决了这个问题。

func updateInterestInJob(_ req: Request) throws -> Future<SeekerInterestInJob> {
    
    var myInterest = SeekerInterestInJob(userId: 0, annotationId: 0, interest: false, status: 0)
    let decoder = JSONDecoder()
    
    guard let data = req.http.body.data else {
        throw req as! Error
    }
    
    do {
        
        myInterest  = try decoder.decode(SeekerInterestInJob.self, from: data)
        print("Testing print")
        
        do {
            return try SeekerInterestInJob.query(on: req).filter(\SeekerInterestInJob.userId, .equal,myInterest.userId).filter(\SeekerInterestInJob.providerId, .equal,myInterest.providerId).filter(\SeekerInterestInJob.annotationId, .equal,myInterest.annotationId).first().flatMap { (foundInterest) -> EventLoopFuture<SeekerInterestInJob> in

                if foundInterest == nil {
                    print("interest not found")
                    return myInterest.save(on: req)
                }
                else {
                    print("interest found")
                    foundInterest?.userId = myInterest.userId
                    foundInterest?.providerId = myInterest.providerId
                    foundInterest?.annotationId = myInterest.annotationId

                    if myInterest.status != 0 {
                        foundInterest?.status = myInterest.status
                        foundInterest?.interest = foundInterest?.interest
                    }
                    else {
                        foundInterest?.interest = myInterest.interest
                    }

                    return (foundInterest?.update(on: req))!
                }
            }
        }
        catch {
            print("in inner catch block")
            return myInterest.update(on: req)
        }
    }
    catch {
        print("in outer catch block")
        return myInterest.update(on: req)
    }
}

嗯,你的问题就在这里,在你的方法的顶部:

guard let data = req.http.body.data else {
    throw req as! Error
}

Vapor 的 Request 类型不符合 Error 协议,因此此类型转换将在 100% 的时间内崩溃。相反,你应该使用 Vapor 的内置 Abort 错误类型,它可以用来表示任何 HTTP 错误。

guard let data = req.http.body.data else {
    throw Abort(.badRequest, reason: "Missing request body")
}