failure crate actually sucks for context, rolling my own simple thing

This commit is contained in:
Dustin Carlino 2018-10-10 16:05:32 -07:00
parent 843742b708
commit 6f33c9a6da
6 changed files with 59 additions and 41 deletions

40
abstutil/src/error.rs Normal file
View File

@ -0,0 +1,40 @@
use std::{error, fmt};
pub struct Error {
message: String,
context: Vec<String>,
}
impl Error {
pub fn new(message: String) -> Error {
Error {
message,
context: Vec::new(),
}
}
pub fn context(mut self, msg: String) -> Error {
self.context.push(msg);
self
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n{}\n", self.message)?;
for c in &self.context {
write!(f, " - {}\n", c)?;
}
write!(f, "\n")?;
Ok(())
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Do the same thing as the Display trait
write!(f, "{}", self)
}
}
impl error::Error for Error {}

View File

@ -5,11 +5,13 @@ extern crate serde_json;
mod abst_multimap; mod abst_multimap;
mod clone; mod clone;
mod error;
mod io; mod io;
mod time; mod time;
pub use abst_multimap::MultiMap; pub use abst_multimap::MultiMap;
pub use clone::Cloneable; pub use clone::Cloneable;
pub use error::Error;
pub use io::{ pub use io::{
deserialize_btreemap, deserialize_multimap, list_all_objects, load_all_objects, read_binary, deserialize_btreemap, deserialize_multimap, list_all_objects, load_all_objects, read_binary,
read_json, save_object, serialize_btreemap, serialize_multimap, to_json, write_binary, read_json, save_object, serialize_btreemap, serialize_multimap, to_json, write_binary,

View File

@ -6,7 +6,6 @@ authors = ["Dustin Carlino <dabreegster@gmail.com>"]
[dependencies] [dependencies]
abstutil = { path = "../abstutil" } abstutil = { path = "../abstutil" }
dimensioned = { git = "https://github.com/paholg/dimensioned", rev = "0e1076ebfa5128d1ee544bdc9754c948987b6fe3", features = ["serde"] } dimensioned = { git = "https://github.com/paholg/dimensioned", rev = "0e1076ebfa5128d1ee544bdc9754c948987b6fe3", features = ["serde"] }
failure = "0.1.2"
flame = "0.2.2" flame = "0.2.2"
geo = "0.9.1" geo = "0.9.1"
geom = { path = "../geom" } geom = { path = "../geom" }

View File

@ -1,7 +1,5 @@
extern crate abstutil; extern crate abstutil;
extern crate dimensioned; extern crate dimensioned;
#[macro_use]
extern crate failure;
extern crate flame; extern crate flame;
extern crate geo; extern crate geo;
extern crate geom; extern crate geom;
@ -48,15 +46,3 @@ pub use traversable::Traversable;
pub use turn::{Turn, TurnID}; pub use turn::{Turn, TurnID};
pub const LANE_THICKNESS: f64 = 2.5; pub const LANE_THICKNESS: f64 = 2.5;
#[derive(Debug, Fail)]
#[fail(display = "{}", reason)]
pub struct MapError {
reason: String,
}
impl MapError {
pub fn new(reason: String) -> MapError {
MapError { reason }
}
}

View File

@ -1,13 +1,14 @@
// Copyright 2018 Google LLC, licensed under http://www.apache.org/licenses/LICENSE-2.0 // Copyright 2018 Google LLC, licensed under http://www.apache.org/licenses/LICENSE-2.0
use abstutil; use abstutil;
use abstutil::Error;
use edits::RoadEdits; use edits::RoadEdits;
use failure::{Error, ResultExt};
use flame; use flame;
use geom::{Bounds, HashablePt2D, PolyLine, Pt2D}; use geom::{Bounds, HashablePt2D, PolyLine, Pt2D};
use make; use make;
use raw_data; use raw_data;
use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io;
use std::path; use std::path;
use { use {
Area, AreaID, Building, BuildingID, BusRoute, BusStop, BusStopID, Intersection, IntersectionID, Area, AreaID, Building, BuildingID, BusRoute, BusStop, BusStopID, Intersection, IntersectionID,
@ -34,7 +35,7 @@ pub struct Map {
} }
impl Map { impl Map {
pub fn new(path: &str, road_edits: RoadEdits) -> Result<Map, Error> { pub fn new(path: &str, road_edits: RoadEdits) -> Result<Map, io::Error> {
// TODO I think I want something a bit different than flame: // TODO I think I want something a bit different than flame:
// - Print as each phase occurs // - Print as each phase occurs
// - Print with nicely formatted durations // - Print with nicely formatted durations
@ -384,7 +385,7 @@ impl Map {
let road = self.get_parent(sidewalk); let road = self.get_parent(sidewalk);
road.find_parking_lane(sidewalk) road.find_parking_lane(sidewalk)
.and_then(|parking| road.find_driving_lane(parking)) .and_then(|parking| road.find_driving_lane(parking))
.context(format!("get_driving_lane_from_bldg({})", bldg)) .map_err(|e| e.context(format!("get_driving_lane_from_bldg({})", bldg)))
} }
pub fn get_sidewalk_from_driving_lane(&self, driving: LaneID) -> Result<LaneID, Error> { pub fn get_sidewalk_from_driving_lane(&self, driving: LaneID) -> Result<LaneID, Error> {
@ -395,7 +396,7 @@ impl Map {
} }
road.find_parking_lane(driving) road.find_parking_lane(driving)
.and_then(|parking| road.find_sidewalk(parking)) .and_then(|parking| road.find_sidewalk(parking))
.context(format!("get_sidewalk_from_driving_lane({})", driving)) .map_err(|e| e.context(format!("get_sidewalk_from_driving_lane({})", driving)))
} }
pub fn get_driving_lane_from_parking(&self, parking: LaneID) -> Result<LaneID, Error> { pub fn get_driving_lane_from_parking(&self, parking: LaneID) -> Result<LaneID, Error> {

View File

@ -1,9 +1,9 @@
use abstutil::Error;
use dimensioned::si; use dimensioned::si;
use failure::Error;
use geom::PolyLine; use geom::PolyLine;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::fmt; use std::fmt;
use {LaneID, LaneType, MapError}; use {LaneID, LaneType};
// TODO reconsider pub usize. maybe outside world shouldnt know. // TODO reconsider pub usize. maybe outside world shouldnt know.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
@ -89,10 +89,10 @@ impl Road {
.find(|pair| pair.1 == LaneType::Sidewalk) .find(|pair| pair.1 == LaneType::Sidewalk)
.map(|pair| pair.0) .map(|pair| pair.0)
.ok_or_else(|| { .ok_or_else(|| {
Error::from(MapError::new(format!( Error::new(format!(
"{} doesn't have sidewalk sibling", "{} doesn't have sidewalk sibling",
parking_or_driving parking_or_driving
))) ))
}) })
} }
@ -102,12 +102,7 @@ impl Road {
.iter() .iter()
.find(|pair| pair.1 == LaneType::Driving) .find(|pair| pair.1 == LaneType::Driving)
.map(|pair| pair.0) .map(|pair| pair.0)
.ok_or_else(|| { .ok_or_else(|| Error::new(format!("{} doesn't have driving lane sibling", parking)))
Error::from(MapError::new(format!(
"{} doesn't have driving lane sibling",
parking
)))
})
} }
// Handles intermediate parking and bus lanes and such // Handles intermediate parking and bus lanes and such
@ -145,10 +140,10 @@ impl Road {
if this_side.len() == 1 && opposite[0].1 == LaneType::Driving { if this_side.len() == 1 && opposite[0].1 == LaneType::Driving {
return Ok(opposite[0].0); return Ok(opposite[0].0);
} }
bail!(MapError::new(format!( Err(Error::new(format!(
"Sidewalk {} doesn't have driving lane", "Sidewalk {} doesn't have driving lane",
sidewalk sidewalk
))); )))
} }
pub fn find_parking_lane(&self, driving: LaneID) -> Result<LaneID, Error> { pub fn find_parking_lane(&self, driving: LaneID) -> Result<LaneID, Error> {
@ -157,12 +152,7 @@ impl Road {
.iter() .iter()
.find(|pair| pair.1 == LaneType::Parking) .find(|pair| pair.1 == LaneType::Parking)
.map(|pair| pair.0) .map(|pair| pair.0)
.ok_or_else(|| { .ok_or_else(|| Error::new(format!("{} doesn't have parking lane sibling", driving)))
Error::from(MapError::new(format!(
"{} doesn't have parking lane sibling",
driving
)))
})
} }
pub fn get_opposite_lane(&self, lane: LaneID, lane_type: LaneType) -> Result<LaneID, Error> { pub fn get_opposite_lane(&self, lane: LaneID, lane_type: LaneType) -> Result<LaneID, Error> {
@ -181,18 +171,18 @@ impl Road {
if let Some(idx) = forwards.iter().position(|id| *id == lane) { if let Some(idx) = forwards.iter().position(|id| *id == lane) {
return backwards.get(idx).map(|id| *id).ok_or_else(|| { return backwards.get(idx).map(|id| *id).ok_or_else(|| {
Error::from(MapError::new(format!( Error::new(format!(
"{} doesn't have opposite lane of type {:?}", "{} doesn't have opposite lane of type {:?}",
lane, lane_type lane, lane_type
))) ))
}); });
} }
if let Some(idx) = backwards.iter().position(|id| *id == lane) { if let Some(idx) = backwards.iter().position(|id| *id == lane) {
return forwards.get(idx).map(|id| *id).ok_or_else(|| { return forwards.get(idx).map(|id| *id).ok_or_else(|| {
Error::from(MapError::new(format!( Error::new(format!(
"{} doesn't have opposite lane of type {:?}", "{} doesn't have opposite lane of type {:?}",
lane, lane_type lane, lane_type
))) ))
}); });
} }
panic!("{} doesn't contain {}", self.id, lane); panic!("{} doesn't contain {}", self.id, lane);