Skip to content

Instantly share code, notes, and snippets.

@krdlab
Created June 13, 2022 14:05
Show Gist options
  • Save krdlab/1938882458de37f7913b6d6893d9730e to your computer and use it in GitHub Desktop.
Save krdlab/1938882458de37f7913b6d6893d9730e to your computer and use it in GitHub Desktop.
Rust custom error
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,
}
}
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