Created
June 13, 2022 14:05
-
-
Save krdlab/1938882458de37f7913b6d6893d9730e to your computer and use it in GitHub Desktop.
Rust custom error
This file contains hidden or 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
pub mod custom { | |
use thiserror::Error; | |
#[derive(Debug, Error)] | |
#[error("{message:} ({line:}, {column:})")] | |
pub struct JsonError { | |
pub message: String, | |
pub line: usize, | |
pub column: usize, | |
} | |
} |
This file contains hidden or 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
use custom_error::custom; | |
use std::fmt; | |
#[derive(Debug, Clone)] | |
pub struct JsonError { | |
pub message: String, | |
pub line: usize, | |
pub column: usize, | |
} | |
impl fmt::Display for JsonError { | |
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { | |
write!(f, "{} ({}:{})", self.message, self.line, self.column) | |
} | |
} | |
impl std::error::Error for JsonError {} | |
fn main() { | |
let x: usize = 100; | |
match TryInto::<u8>::try_into(x) { | |
Ok(y) => println!("{}", y), | |
Err(e) => println!("{}", e), | |
} | |
println!("{:?}", test()); | |
} | |
fn test() -> Result<(), custom::JsonError> { | |
Err(custom::JsonError { | |
message: "hoge".to_string(), | |
line: 1, | |
column: 1, | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment