Last active
January 6, 2017 14:32
-
-
Save ChrisBuchholz/473be0bd545c8c5edd5cd3232e045e40 to your computer and use it in GitHub Desktop.
swift and rust error handling
This file contains 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
// run with `cargo script errors.rs` | |
#[derive(Debug)] | |
pub enum AError { | |
SomeError, | |
} | |
pub enum Ado { | |
A, | |
B, | |
} | |
pub fn a(ado: Ado) -> Result<String, AError> { | |
match ado { | |
Ado::A => Err(AError::SomeError), | |
Ado::B => Ok("Test".to_string()), | |
} | |
} | |
pub fn b(ado: Ado) -> Result<String, AError> { | |
let s = a(ado)?; | |
Ok(format!("got success `{}`", s)) | |
} | |
fn main() { | |
println!("{:?}", b(Ado::A)); // outputs Err(SomeError) | |
println!("{:?}", b(Ado::B)); // outputs Ok("got success `Test`") | |
} |
This file contains 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
// run with `cat lib.swift errors.swift | swift -` | |
public enum AError: Error { | |
case SomeError | |
} | |
public enum Ado { | |
case A, B | |
} | |
public func a(_ ado: Ado) throws -> String { | |
switch ado { | |
case .A: throw AError.SomeError | |
case .B: return "Test" | |
} | |
} | |
public func b(_ ado: Ado) throws -> String { | |
let s = try a(ado) | |
return "got success `\(s)`" | |
} | |
print(try b(Ado.A)^) // output Err(main.AError.SomeError) | |
print(try b(Ado.B)^) // output Ok("got success `Test`") |
This file contains 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
// boilerplate Result type and the try-lift ^^ operator for errors.swift | |
public enum Result<T> { | |
case Ok(T) | |
case Err(Error) | |
} | |
postfix operator ^ | |
postfix func ^<T>(_ c: @autoclosure () throws -> T) -> Result<T> { | |
do { | |
return .Ok(try c()) | |
} catch { | |
return .Err(error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment