2020-12-25 04:16:34 +00:00
|
|
|
//! Error handling with `Error`, `NcResult` & `NcIntResult` for error handling
|
2020-12-02 13:01:09 +00:00
|
|
|
|
2020-12-25 04:16:34 +00:00
|
|
|
use std::{self, error, fmt};
|
|
|
|
|
|
|
|
/// The [`i32`] value used to return errors by the underlying C API.
|
|
|
|
///
|
|
|
|
/// A value < 0 means error, (usually -1).
|
2020-12-19 17:01:28 +00:00
|
|
|
///
|
|
|
|
/// # Defined constants:
|
|
|
|
///
|
|
|
|
/// - [`NCRESULT_OK`]
|
|
|
|
/// - [`NCRESULT_ERR`]
|
|
|
|
/// - [`NCRESULT_MAX`]
|
2020-12-25 04:16:34 +00:00
|
|
|
pub type NcIntResult = i32;
|
2020-12-02 13:01:09 +00:00
|
|
|
|
2020-12-25 04:16:34 +00:00
|
|
|
/// OK value, for the functions that return [`NcIntResult`].
|
2020-12-02 13:01:09 +00:00
|
|
|
pub const NCRESULT_OK: i32 = 0;
|
|
|
|
|
2020-12-25 04:16:34 +00:00
|
|
|
/// ERROR value, for the functions that return an [`NcIntResult`].
|
2020-12-02 13:01:09 +00:00
|
|
|
pub const NCRESULT_ERR: i32 = -1;
|
2020-12-19 17:01:28 +00:00
|
|
|
|
2020-12-25 04:16:34 +00:00
|
|
|
/// MAX value, for the functions that return [`NcIntResult`].
|
2020-12-19 17:01:28 +00:00
|
|
|
pub const NCRESULT_MAX: i32 = i32::MAX;
|
2020-12-25 04:16:34 +00:00
|
|
|
|
|
|
|
/// The error type for the Rust methods API.
|
2020-12-25 16:40:37 +00:00
|
|
|
#[derive(Debug, Clone, Default)]
|
2020-12-25 04:16:34 +00:00
|
|
|
pub struct NcError {
|
2020-12-26 02:58:55 +00:00
|
|
|
/// [NcIntResult].
|
2020-12-25 04:16:34 +00:00
|
|
|
pub int: i32,
|
2020-12-25 16:40:37 +00:00
|
|
|
pub msg: String,
|
2020-12-25 04:16:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for NcError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
2020-12-26 02:58:55 +00:00
|
|
|
write!(f, "NcError {}: {}", self.int, self.msg)
|
2020-12-25 04:16:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl error::Error for NcError {
|
|
|
|
fn description(&self) -> &str {
|
|
|
|
&self.msg
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl NcError {
|
|
|
|
/// New NcError.
|
2020-12-25 16:40:37 +00:00
|
|
|
pub fn new(int: NcIntResult) -> Self {
|
|
|
|
Self {
|
|
|
|
int,
|
|
|
|
..Default::default()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/// New NcError with message.
|
|
|
|
pub fn with_msg(int: NcIntResult, msg: &str) -> Self {
|
2020-12-25 04:16:34 +00:00
|
|
|
Self {
|
|
|
|
int,
|
|
|
|
msg: msg.to_string(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The result type for the Rust methods API.
|
|
|
|
pub type NcResult<T> = Result<T, NcError>;
|