包裹错误

把错误装箱这种做法也可以改成把它包裹到你自己的错误类型中。

  1. use std::error;
  2. use std::num::ParseIntError;
  3. use std::fmt;
  4. type Result<T> = std::result::Result<T, DoubleError>;
  5. #[derive(Debug)]
  6. enum DoubleError {
  7. EmptyVec,
  8. // 在这个错误类型中,我们采用 `parse` 的错误类型中 `Err` 部分的实现。
  9. // 若想提供更多信息,则该类型中还需要加入更多数据。
  10. Parse(ParseIntError),
  11. }
  12. impl fmt::Display for DoubleError {
  13. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  14. match *self {
  15. DoubleError::EmptyVec =>
  16. write!(f, "please use a vector with at least one element"),
  17. // 这是一个封装(wrapper),它采用内部各类型对 `fmt` 的实现。
  18. DoubleError::Parse(ref e) => e.fmt(f),
  19. }
  20. }
  21. }
  22. impl error::Error for DoubleError {
  23. fn description(&self) -> &str {
  24. match *self {
  25. DoubleError::EmptyVec => "empty vectors not allowed",
  26. // 这已经实现了 `Error`,所以采用它自己的实现。
  27. DoubleError::Parse(ref e) => e.description(),
  28. }
  29. }
  30. fn cause(&self) -> Option<&error::Error> {
  31. match *self {
  32. DoubleError::EmptyVec => None,
  33. // 原因采取内部对错误类型的实现。它隐式地转换成了 trait 对象 `&error:Error`。
  34. // 这可以工作,因为内部的类型已经实现了 `Error` trait。
  35. DoubleError::Parse(ref e) => Some(e),
  36. }
  37. }
  38. }
  39. // 实现从 `ParseIntError` 到 `DoubleError` 的转换。
  40. // 在使用 `?` 时,或者一个 `ParseIntError` 需要转换成 `DoubleError` 时,它会被自动调用。
  41. impl From<ParseIntError> for DoubleError {
  42. fn from(err: ParseIntError) -> DoubleError {
  43. DoubleError::Parse(err)
  44. }
  45. }
  46. fn double_first(vec: Vec<&str>) -> Result<i32> {
  47. let first = vec.first().ok_or(DoubleError::EmptyVec)?;
  48. let parsed = first.parse::<i32>()?;
  49. Ok(2 * parsed)
  50. }
  51. fn print(result: Result<i32>) {
  52. match result {
  53. Ok(n) => println!("The first doubled is {}", n),
  54. Err(e) => println!("Error: {}", e),
  55. }
  56. }
  57. fn main() {
  58. let numbers = vec!["42", "93", "18"];
  59. let empty = vec![];
  60. let strings = vec!["tofu", "93", "18"];
  61. print(double_first(numbers));
  62. print(double_first(empty));
  63. print(double_first(strings));
  64. }

这种做法会在错误处理中增加一些模板化的代码,而且也不是所有的应用都需要这样做。一些 库可以帮你处理模板化代码的问题。

See also:

From::from and 枚举类型