从这样的函数中抛出错误的正确方法是什么:
func fetch(by id: String, page: Int = 1) -> Promise<ProductReviewBase> {
// call api
guard let url = URL(string: "") else {
return Promise { _ in return IntegrationError.invalidURL }
}
return query(with: url)
}我搞不懂是让这个函数引发错误,还是返回一个返回错误的承诺。谢谢
发布于 2018-11-02 01:17:35
我真的讨厌把隐喻混在一起的界面。如果您要返回一个承诺,那么使用允诺的错误系统。如果你想要更多的理由而不是我的仇恨,那么想象一下它在呼叫站点上会是什么样子:
do {
(try fetch(by: id))
.then {
// do something
}
.catch { error in
// handle error
}
}
catch {
// handle error
}vs
fetch(by: id)
.then {
// do something
}
.catch { error in
// handle error
}后者看起来要干净得多。
下面是编写示例函数的最佳方法(IMO):
func fetch(by id: String, page: Int = 1) -> Promise<ProductReviewBase> {
guard let url = URL(string: "") else { return Promise(error: IntegrationError.invalidURL) }
return query(with: url)
}https://stackoverflow.com/questions/53111396
复制相似问题