diff options
author | Vincent Ambo <mail@tazj.in> | 2018-09-26T21·18+0200 |
---|---|---|
committer | Vincent Ambo <mail@tazj.in> | 2018-09-26T21·18+0200 |
commit | c4b94d8d2dc00c0742cf7af1c0fd2c1256f75078 (patch) | |
tree | 6d9a7cbd32de151fb007969b533dd58180c71ba2 /finito-door/src | |
parent | 37590ae0f61187f080fe5b09d037ad428b4b1db4 (diff) |
feat(door): Use failure::Error as associated error type
Implements the associated error type for the FSM trait as failure::Error. This makes it possible to fail gracefully in all actions, for example in the updated definition of the `NotifyIRC` action which now appends to a file.
Diffstat (limited to 'finito-door/src')
-rw-r--r-- | finito-door/src/lib.rs | 24 |
1 files changed, 19 insertions, 5 deletions
diff --git a/finito-door/src/lib.rs b/finito-door/src/lib.rs index 074556c76148..e6a3099e9efa 100644 --- a/finito-door/src/lib.rs +++ b/finito-door/src/lib.rs @@ -72,6 +72,8 @@ //! Alright, enough foreplay, lets dive in! #[macro_use] extern crate serde_derive; + +extern crate failure; extern crate finito; use finito::FSM; @@ -170,6 +172,11 @@ impl FSM for DoorState { type Event = DoorEvent; type Action = DoorAction; + // For error handling, the door simply uses `failure` which provides a + // generic, chainable error type. In real-world implementations you may want + // to use a custom error type or similar. + type Error = failure::Error; + // The implementation of `handle` provides us with the actual transition // logic of the door. // @@ -254,18 +261,25 @@ impl FSM for DoorState { // Additionally the `act` function can return new events. This is useful for // a sort of "callback-like" pattern (cause an action to fetch some data, // receive it as an event) but is not used in this example. - fn act(action: DoorAction) -> Vec<DoorEvent> { + fn act(action: DoorAction) -> Result<Vec<DoorEvent>, failure::Error> { match action { DoorAction::NotifyIRC(msg) => { - // TODO: write to file in example - println!("IRC: {}", msg); - vec![] + use std::fs::OpenOptions; + use std::io::Write; + + let mut file = OpenOptions::new() + .append(true) + .create(true) + .open("/tmp/door-irc.log")?; + + write!(file, "<doorbot> {}\n", msg)?; + Ok(vec![]) } DoorAction::CallThePolice => { // TODO: call the police println!("The police was called! For real!"); - vec![] + Ok(vec![]) } } } |