Tropical Storm Error-ca #swiftlang

When you extend String to support ErrorType, you can just throw strings as errors. Does it get any simpler than this?

extension String: ErrorType {}
func raiseError(reason : String) throws {
    throw reason}
do {try raiseError("immediate failpoint")} 
    catch {print(error)}

Actually, I’m kind of fond of this too:

extension String: ErrorType {}
extension ErrorType {
    public func contextString(
        file : String = __FILE__, 
        function : String = __FUNCTION__, 
        line : Int = __LINE__) -> String {
        return "\(function):\(file):\(line) \(self)"
func raiseError() throws {
    throw "failpoint".contextString()}
do {try raiseError()} catch {print(error)}

Comments are closed.