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

标签 swift error-handling vapor

我有 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/

相关文章:

swift - 自定义 MKAnnotation 字典输入 (CLLocationCooperative2d)

ios - 如何解除分配从 Swift 结构引用的 UnsafeMutablePointer

ios - SwiftUI 导航链接和 ScrollView 问题

ios - UITest 本地化应用程序

java返回类型错误及错误处理

c# - 处理 Task 中的异常

php - laravel 5.4 auth注册自定义错误消息

swift - 如何在 Linux 上的 Swift 中更改进程标题?

Vapor 3 : transform array of Future object to an array of Future other objects

postgresql - 适用于 Postgres 的 Vapor 3/Fluent : How do I make a SELECT DISTINCT query?