Skip to content

Instantly share code, notes, and snippets.

@masakih
Last active June 10, 2022 11:20
Show Gist options
  • Select an option

  • Save masakih/aec9a3616eae6c1123395b4a8c073061 to your computer and use it in GitHub Desktop.

Select an option

Save masakih/aec9a3616eae6c1123395b4a8c073061 to your computer and use it in GitHub Desktop.
発展させてみた #CodePiece
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