Skip to content

Instantly share code, notes, and snippets.

@weissi
Created April 12, 2019 10:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weissi/d861bed9cad17871c3ad814911feeafb to your computer and use it in GitHub Desktop.
Save weissi/d861bed9cad17871c3ad814911feeafb to your computer and use it in GitHub Desktop.
import Foundation
public struct SandwichError: Error, Equatable, CustomStringConvertible {
private enum SandwichErrorCode: Int {
case tooLittleSalami = 1
case tooLittleMustard
case noTomatoes
case noBread
}
private var code: SandwichErrorCode
private init(code: SandwichErrorCode) {
self.code = code
}
public var description: String {
return "SandwichError.\(String(describing: self.code))"
}
public static let tooLittleSalami: SandwichError = .init(code: .tooLittleSalami)
public static let tooLittleMustard: SandwichError = .init(code: .tooLittleMustard)
public static let noTomatoes: SandwichError = .init(code: .noTomatoes)
public static let noBread: SandwichError = .init(code: .noBread)
}
func inspectErrorWithSwitch(_ error: Error) {
if let error = error as? SandwichError {
switch error {
case .tooLittleSalami:
print("NEED MORE SALAMI!")
case .tooLittleMustard:
print("NEED MORE MUSTARD!")
case .noTomatoes:
print("Can I please get a tomato?")
default:
print("ooh, some error I didn't know existed: \(error)")
}
} else {
print("totally unexpected error")
}
}
func inspectErrorWithCatch(_ e: Error) {
do {
throw e
} catch let error as SandwichError where error == .tooLittleSalami {
print("NEED MORE SALAMI!")
} catch let error as SandwichError where error == .tooLittleMustard {
print("NEED MORE MUSTARD!")
} catch let error as SandwichError where error == .noTomatoes {
print("Can I please get a tomato?")
} catch let error as SandwichError {
print("ooh, some error I didn't know existed: \(error)")
} catch {
print("totally unexpected error")
}
}
inspectErrorWithSwitch(SandwichError.tooLittleSalami)
inspectErrorWithSwitch(SandwichError.tooLittleMustard)
inspectErrorWithSwitch(SandwichError.noTomatoes)
inspectErrorWithSwitch(SandwichError.noBread)
inspectErrorWithSwitch(NSError())
inspectErrorWithCatch(SandwichError.tooLittleSalami)
inspectErrorWithCatch(SandwichError.tooLittleMustard)
inspectErrorWithCatch(SandwichError.noTomatoes)
inspectErrorWithCatch(SandwichError.noBread)
inspectErrorWithCatch(NSError())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment