Created
November 14, 2016 02:23
-
-
Save ukitaka/39ae8a30be87409c608ba40b06f670e7 to your computer and use it in GitHub Desktop.
Observableでエラーの型を明示的に扱いたい
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
import RxSwift | |
import Result | |
protocol RxError: Error { | |
init(anyError: Error) | |
} | |
typealias ObservableE<T, E: RxError> = Observable<Result<T, E>> | |
extension Observable { | |
func asObservableE<Err: RxError>() -> ObservableE<E, Err> { | |
return self | |
.map(Result<E, Err>.success) | |
.catchError { error -> ObservableE<E, Err> in | |
return ObservableE.just(Result.failure(Err(anyError: error))) | |
} | |
} | |
} |
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
struct InvalidJSONFormatError: Error { | |
let data: Data | |
let urlResponse: HTTPURLResponse | |
} | |
struct ValidationError: Error { | |
let errors: [ValidationErrorInfo] | |
} | |
struct ValidationErrorInfo: Error { | |
let code: Int | |
let message: String | |
} | |
enum WebAPIError: RxError { | |
case networkError | |
case invalidJSONFormat(InvalidJSONFormatError) | |
case validationError(ValidationError) | |
case unknownError(Error) | |
init(anyError: Error) { | |
// できればas使わずにやりたかった | |
switch anyError { | |
case let error as InvalidJSONFormatError: | |
self = .invalidJSONFormat(error) | |
case let error as ValidationError: | |
self = .validationError(error) | |
case let error as NSError where error.code == 3840: | |
self = .networkError | |
default: | |
self = .unknownError(anyError) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
あとは
ObservableE
に対してがんばってオペレータを生やしたい。要はこういうシグネチャのやつが欲しい。