aboutsummaryrefslogtreecommitdiffstats
path: root/crates/yt_dlp/src/python_error.rs
blob: 967a1a57454c8ba59ebeb0b1fd10eb7f0a81bcc1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// Copyright (C) 2026 Soispha Peetz <soispha@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Yt.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use std::fmt::{self, Display};

use log::{Level, debug, log_enabled};
use pyo3::{PyErr, Python, types::PyTracebackMethods};

#[derive(thiserror::Error, Debug)]
pub struct PythonError {
    pub python_error_message: String,
    context: &'static str,
}

pub(crate) trait IntoPythonError<T>: Sized {
    fn wrap_exc(self, py: Python<'_>, context: &'static str) -> Result<T, PythonError>;
}

impl<T> IntoPythonError<T> for Result<T, PyErr> {
    fn wrap_exc(self, py: Python<'_>, context: &'static str) -> Result<T, PythonError> {
        self.map_err(|exc| PythonError::from_exception(py, &exc, context))
    }
}

impl Display for PythonError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Python threw an exception: {} (while {})",
            self.python_error_message, self.context
        )
    }
}

impl PythonError {
    pub(super) fn from_exception(py: Python<'_>, exc: &PyErr, context: &'static str) -> Self {
        let buffer = process_exception(py, exc);
        Self {
            python_error_message: buffer,
            context,
        }
    }
}

pub(super) fn process_exception(py: Python<'_>, err: &PyErr) -> String {
    if log_enabled!(Level::Debug) {
        let mut output = err.to_string();

        if let Some(tb) = err.traceback(py) {
            output.push('\n');
            output.push_str(&tb.format().unwrap());
        }

        debug!("Python threw an exception: {output}");
    }

    err.to_string()
}