Created
November 20, 2016 08:36
-
-
Save ukitaka/685ce13861d38f63b2fceca915c21a09 to your computer and use it in GitHub Desktop.
Error definition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 前提とか | |
// ・micro frameworks | |
// ・DDDのレイヤー化方針に沿ってレイヤー化 | |
// ・RxじゃなくてFuture<T, E: Error>を使ってたときの話 | |
// ・つまりエラー型を明示的に扱う | |
// ・throwsは型が明確にならないので使わない | |
// ---------- | |
// 1. 各モジュールはそのモジュールが返しうるエラー型をenumで作る | |
// ---------- | |
// APIのエラー | |
enum WebAPIError: Error { | |
... | |
} | |
// Realm関連で発生したエラー | |
enum RealmError: Error { | |
... | |
} | |
// ---------- | |
// 2. 各レイヤーごとに発生しうるエラーをまとめるenumを作る | |
// ---------- | |
enum InfraLayerError: Error { | |
case webAPIError(WebAPIError) | |
case RealmError(RealmError) | |
... | |
} | |
enum DomainLayerError: Error { | |
case infraLayerError(InfraLayerError) | |
case entityNotFound(...) | |
... | |
} | |
// ---------- | |
// 3. 各レイヤーが上位レイヤーに公開するI/Fには2.で定義したエラーを使う | |
// ・マッピングする | |
// ・上位レイヤーに公開する必要がなければ拾って処理するなどする | |
// ---------- | |
final class UserRepository { | |
func findByID(userID: UserID) -> Future<User, DomainLayerError> { | |
return apiClient.request(...) | |
... | |
.mapError(DomainLayerError.hoge.fuga) // DomainLayerErrorにマッピングする | |
} | |
} | |
// ---------- | |
// 4. UIレイヤで表示するときもパターンマッチで安全に扱えて幸せ | |
// ---------- | |
func showErrorDialog(error: AppError) -> Future<Void, NoError> { | |
switch error { | |
case .domainLayerError(let error) | |
return showDomainLayerErrorDialog(error) | |
} | |
... | |
} | |
private func showDomainLayerErrorDialog(error: DomainLayerError) -> Future<Void, NoError> { | |
switch error { | |
case .infraLayerError(let error) | |
return showInfraLayerError(error) | |
} | |
... | |
} | |
private func showInfraLayerErrorDialog(error: InfraLayerError) -> Future<Void, NoError> { | |
switch error { | |
case .webAPIError(let error) | |
showWebAPIErrorDialog(error) | |
} | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment