From c4b94d8d2dc00c0742cf7af1c0fd2c1256f75078 Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Wed, 26 Sep 2018 23:18:26 +0200 Subject: 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. --- finito-door/src/lib.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) (limited to 'finito-door/src/lib.rs') 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 { + fn act(action: DoorAction) -> Result, 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, " {}\n", msg)?; + Ok(vec![]) } DoorAction::CallThePolice => { // TODO: call the police println!("The police was called! For real!"); - vec![] + Ok(vec![]) } } } -- cgit 1.4.1