我有Vapor 3服务器api和iOS应用程序。例如,当我向服务器发出请求并抛出一个错误时(我将它抛到服务器上):
throw Abort(.badRequest)在response error == nil中的error == nil应用程序中,如果我将响应数据转换为字符串,我可以看到:
{“错误”:真,“原因”:“不良请求”}
我试图将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()
}
}
}我想从请求中得到错误作为错误。不是在数据里。
发布于 2019-08-03 06:23:30
您只需检查响应代码,而不是错误。
https://stackoverflow.com/questions/57335147
复制相似问题