首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vapor服务器抛出的错误以字符串形式出现,而不是响应错误。

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

Stack Overflow用户
提问于 2019-08-03 02:59:08
回答 1查看 810关注 0票数 1

我有Vapor 3服务器api和iOS应用程序。例如,当我向服务器发出请求并抛出一个错误时(我将它抛到服务器上):

代码语言:javascript
复制
throw Abort(.badRequest)

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

{“错误”:真,“原因”:“不良请求”}

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

代码语言:javascript
复制
// 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()
}
代码语言:javascript
复制
// 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()
        }

    }
}

我想从请求中得到错误作为错误。不是在数据里。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-03 06:23:30

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57335147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档