Last active
June 10, 2022 11:20
-
-
Save masakih/aec9a3616eae6c1123395b4a8c073061 to your computer and use it in GitHub Desktop.
発展させてみた #CodePiece
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 GeneratedError<T>: Error { | |
| let host: T | |
| let id: Int | |
| let message: String | |
| let file: String | |
| let line: Int | |
| init(_ host: T, id: Int = 0, message: String = "", file: String, line: Int) { | |
| self.host = host | |
| self.id = id | |
| self.message = message | |
| self.file = file | |
| self.line = line | |
| } | |
| } | |
| extension GeneratedError: CustomStringConvertible { | |
| var description: String { | |
| """ | |
| GeneratedError { | |
| host: \(host), | |
| id: \(id), | |
| message: "\(message)" | |
| positiion: \(file)#\(line) | |
| } | |
| """ | |
| } | |
| } | |
| protocol ErrorGenaratable {} | |
| extension ErrorGenaratable { | |
| func generateError(_ id: Int, _ message: String, file: String = #file, line: Int = #line) -> GeneratedError<Self> { | |
| .init(self, id: id, message: message, file: file, line: line) | |
| } | |
| func generateError(_ id: Int, file: String = #file, line: Int = #line) -> GeneratedError<Self> { | |
| .init(self, id: id, file: file, line: line) | |
| } | |
| func generateError(file: String = #file, line: Int = #line) -> GeneratedError<Self> { | |
| .init(self, file: file, line: line) | |
| } | |
| } | |
| struct Hoge: ErrorGenaratable { | |
| func hoge() throws { | |
| throw generateError() | |
| } | |
| } | |
| struct Fuga: ErrorGenaratable { | |
| func fuga0() throws { | |
| throw generateError(0) | |
| } | |
| func fuga1() throws { | |
| throw generateError(1) | |
| } | |
| } | |
| do { | |
| try Fuga().fuga0() | |
| try Hoge().hoge() | |
| try Fuga().fuga1() | |
| } | |
| catch let error as GeneratedError<Hoge> { | |
| print(error) | |
| } | |
| catch let error as GeneratedError<Fuga> { | |
| switch error.id { | |
| case 0: print("Fuga id 0\n", error) | |
| case 1: print("Fuga id 1\n", error) | |
| default: print("Unknown\n", error) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment