gpt4 book ai didi

swift - Vapor 服务器抛出的错误以字符串形式出现,而不是响应中的错误

转载 作者:行者123 更新时间:2023-11-28 05:39:32 25 4
gpt4 key购买 nike

我有 Vapor 3 服务器 api 和 iOS 应用程序。当我向服务器发出请求并抛出这样的错误时(我把它扔到服务器上):

throw Abort(.badRequest)

在 iOS 应用中响应 error == nil,如果我将响应数据转换为字符串,我可以看到:

{"error":true,"reason":"Bad Request"}

我尝试将 ErrorMiddleware 添加到服务中。这对我不起作用。

// Request on iOS side:
func saveComment(post: Post, text: String, completion: @escaping (Result<Comment, Error>) -> Void) {

var cmps = urlComps
cmps.path = "/api/save-post"

let url = cmps.url!

var request = URLRequest(url: url)
request.httpMethod = HTTPMethod.post
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

struct NewComment: Codable {
let postId: String
let text: String
}

let newComment = NewComment(postId: post.id.uuidString, text: text)
let body = try! JSONEncoder().encode(newComment)

request.httpBody = body

let session = URLSession.shared.dataTask(with: request) { data, response, err in
// this error comes as nil
if let err = err {
completion(.failure(err))
return
}

// if I do String(data: data!, encoding: .utf8)!
// it becomes: {"error":true,"reason":"Bad Request"}

do {
let comment = try JSONDecoder().decode(Comment.self, from: data!)
completion(.success(comment))

} catch {
completion(.failure(error))
}
}

session.resume()
}
// Response on Vapor server side:
func addComment(req: Request) throws -> Future<Comment.FormattedComment> {

let user = try req.requireAuthenticated(User.self)

guard user.canAddComments > 0 else { throw Abort(.badRequest) }
// here I throw error

return try req.content.decode(Comment.NewComment.self).flatMap(to: Comment.FormattedComment.self) { comment in

let newComment = Comment(id: nil, userId: user.id!, postId: comment.postId, text: comment.text, date: Date(), isGiven: false)
return newComment.save(on: req).map {
return $0.formatted()
}

}
}

我想从请求中获取错误作为错误。不在数据中。

最佳答案

您只需要检查响应代码而不是错误。

关于swift - Vapor 服务器抛出的错误以字符串形式出现,而不是响应中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57335147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com