What is the proper way to throw an error from a function like this:
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)
}
I'm confused whether to make this a function that throws an error, or return a promise that returns an error. Thanks
I really hate interfaces that mix metaphors. If you are going to return a promise, then use the promise's error system. If you want more justification than my hatred, then visualize what it would look like at the call site:
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
}
The latter looks a whole lot cleaner.
Here's the best way (IMO) to write your example function:
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)
}