ios - 结合:如何从保护前提条件中提前退出错误
问题描述
我想创建一个方法authenticate
,使用组合,允许用户使用我的 API 登录。
我现在正在尝试添加一个先决条件,这样如果提供的用户名为空,我的方法就不会触及网络。我想在这一点上提前存在,向订阅者提供一个错误。
请在下面找到我的代码片段。我如何从第 4 行的早期存在返回错误?
func authenticate(username: String, password: String) -> AnyPublisher<User, Error> {
guard !username.isEmpty else {
// How to return an error to the subscribers from here?????
return
}
let parameters: [String: Any] = [
"username": username,
"password": password
]
var request = URLRequest(endpoint: Endpoint.login)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
return URLSession.shared.dataTaskPublisher(for: request)
.map { $0.data }
.decode(type: AuthenticationResult.self, decoder: JSONDecoder())
.map { $0.user }
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
解决方案
您可以使用Fail
,这是一种Publisher
:
return Fail(error: MyError.missingUsername).eraseToAnyPublisher()
推荐阅读
- regex - 使用 Pyspark,两个字符之间的正则表达式获取文本和数字,但不是日期
- selenium - Selenium 在 Docker 中由于浏览上下文而崩溃已被丢弃
- c++ - 双重数学和布尔检查给出错误的答案
- javascript - 将字符串作为排序块返回 - Codewars 挑战 - JavaScript
- javascript - 无法从类中调用函数 - 函数无法识别
- reactjs - Redux:状态只在一个地方更新
- linux - 按条目的时间戳对 grep 结果进行排名
- python - 你能看一下下面的代码吗,它不起作用并弹出:“TypeError: unsupported operand type(s) for /: 'str' and 'int'”。请
- javascript - 如何使用 jQuery 选择用于 .empty() 的输入?
- typescript - Linq TypeScript 三元运算符 - 是否可以在不重复代码的情况下重新使用条件作为第一个表达式?