Skip to main content

llama_cpp_error_chain/
error_chain.rs

1use std::error::Error;
2
3/// The message of `error` followed by the message of every error in its source chain.
4#[must_use]
5pub fn error_chain(error: &dyn Error) -> String {
6    let mut chain = error.to_string();
7    let mut source = error.source();
8
9    while let Some(cause) = source {
10        chain.push_str(": ");
11        chain.push_str(&cause.to_string());
12        source = cause.source();
13    }
14
15    chain
16}
17
18#[cfg(test)]
19mod tests {
20    use std::ffi::CString;
21
22    use super::error_chain;
23
24    #[test]
25    fn an_error_without_a_source_is_its_own_message() {
26        let not_utf8 = String::from_utf8(vec![0xff]).unwrap_err().utf8_error();
27
28        assert_eq!(
29            error_chain(&not_utf8),
30            "invalid utf-8 sequence of 1 bytes from index 0"
31        );
32    }
33
34    #[test]
35    fn every_source_follows_the_message_it_caused() {
36        let not_utf8 = CString::new(vec![0xff]).unwrap().into_string().unwrap_err();
37
38        assert_eq!(
39            error_chain(&not_utf8),
40            "C string contained non-utf8 bytes: invalid utf-8 sequence of 1 bytes from index 0"
41        );
42    }
43}