52 lines
1.5 KiB
Rust
52 lines
1.5 KiB
Rust
//! JSON 错误类型。
|
|
//! JSON error type.
|
|
|
|
use std::fmt;
|
|
|
|
/// 解析或序列化 JSON 时产生的错误。
|
|
/// Errors produced while parsing or serializing JSON.
|
|
#[derive(Debug)]
|
|
pub struct JsonError {
|
|
/// 人类可读的错误描述。
|
|
/// Human-readable description of the error.
|
|
pub message: String,
|
|
/// 触发错误的字节偏移量(若可用)。
|
|
/// Byte offset where the error occurred, if known.
|
|
pub position: Option<usize>,
|
|
}
|
|
|
|
impl fmt::Display for JsonError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self.position {
|
|
Some(pos) => write!(f, "JSON error at byte {}: {}", pos, self.message),
|
|
None => write!(f, "JSON error: {}", self.message),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for JsonError {}
|
|
|
|
impl JsonError {
|
|
/// 创建一个不带位置信息的错误。
|
|
/// Create an error with no position information.
|
|
pub fn new(message: impl Into<String>) -> Self {
|
|
Self {
|
|
message: message.into(),
|
|
position: None,
|
|
}
|
|
}
|
|
|
|
/// 创建一个带字节偏移位置的错误。
|
|
/// Create an error with a byte-offset position.
|
|
pub fn at(message: impl Into<String>, position: usize) -> Self {
|
|
Self {
|
|
message: message.into(),
|
|
position: Some(position),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// JSON 操作的 `Result` 便捷别名。
|
|
/// Convenience `Result` alias for JSON operations.
|
|
pub type JsonResult<T> = Result<T, JsonError>;
|