core_foundation/
error.rs

1// Copyright 2016 The Servo Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10//! Core Foundation errors.
11
12pub use core_foundation_sys::error::*;
13
14use std::error::Error;
15use std::fmt;
16
17use crate::base::{CFIndex, TCFType};
18use crate::string::CFString;
19
20declare_TCFType! {
21    /// An error value.
22    CFError, CFErrorRef
23}
24impl_TCFType!(CFError, CFErrorRef, CFErrorGetTypeID);
25
26impl fmt::Debug for CFError {
27    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
28        fmt.debug_struct("CFError")
29            .field("domain", &self.domain())
30            .field("code", &self.code())
31            .field("description", &self.description())
32            .finish()
33    }
34}
35
36impl fmt::Display for CFError {
37    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
38        write!(fmt, "{}", self.description())
39    }
40}
41
42impl Error for CFError {
43    fn description(&self) -> &str {
44        "a Core Foundation error"
45    }
46}
47
48impl CFError {
49    /// Returns a string identifying the domain with which this error is
50    /// associated.
51    pub fn domain(&self) -> CFString {
52        unsafe {
53            let s = CFErrorGetDomain(self.0);
54            CFString::wrap_under_get_rule(s)
55        }
56    }
57
58    /// Returns the code identifying this type of error.
59    pub fn code(&self) -> CFIndex {
60        unsafe { CFErrorGetCode(self.0) }
61    }
62
63    /// Returns a human-presentable description of the error.
64    pub fn description(&self) -> CFString {
65        unsafe {
66            let s = CFErrorCopyDescription(self.0);
67            CFString::wrap_under_create_rule(s)
68        }
69    }
70}