Skip to content

Commit

Permalink
refactor: io errors
Browse files Browse the repository at this point in the history
  • Loading branch information
h-a-n-a committed Dec 5, 2023
1 parent 35be7b3 commit 61772dc
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 100 deletions.
32 changes: 10 additions & 22 deletions crates/rspack_core/src/resolver/resolver_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use std::{
sync::Arc,
};

use rspack_error::{internal_error, Error, InternalError, Severity, TraceableError};
use rspack_error::{
internal_error, DiagnosticError, Error, InternalError, Severity, TraceableError,
};
use rspack_loader_runner::DescriptionData;
use sugar_path::SugarPath;

Expand Down Expand Up @@ -374,24 +376,17 @@ fn map_nodejs_resolver_error(
plugin_driver: &SharedPluginDriver,
) -> ResolveError {
match error {
nodejs_resolver::Error::Io(error) => {
ResolveError(error.to_string(), Error::Io { source: error })
}
nodejs_resolver::Error::Io(error) => ResolveError(error.to_string(), Error::from(error)),
nodejs_resolver::Error::UnexpectedJson((json_path, error)) => ResolveError(
format!(
"{error:?} in {}",
json_path.relative(&plugin_driver.options.context).display()
),
Error::Anyhow {
source: anyhow::Error::msg(format!("{error:?} in {json_path:?}")),
},
),
nodejs_resolver::Error::UnexpectedValue(error) => ResolveError(
error.clone(),
Error::Anyhow {
source: anyhow::Error::msg(error),
},
internal_error!("{error:?} in {json_path:?}"),
),
nodejs_resolver::Error::UnexpectedValue(error) => {
ResolveError(error.clone(), internal_error!(error))
}
nodejs_resolver::Error::CantFindTsConfig(path) => ResolveError(
format!("{} is not a tsconfig", path.display()),
internal_error!("{} is not a tsconfig", path.display()),
Expand All @@ -414,18 +409,11 @@ fn map_oxc_resolver_error(
"Export should be relative path and start with \"./\", but got {}",
specifier
);
ResolveError(
message.clone(),
Error::Anyhow {
source: anyhow::Error::msg(message),
},
)
ResolveError(message.clone(), internal_error!(message))
}
oxc_resolver::ResolveError::IOError(error) => ResolveError(
"IOError".to_string(),
Error::Io {
source: error.into(),
},
Error::InternalError(DiagnosticError(error.into()).into()),
),
oxc_resolver::ResolveError::Builtin(error) => ResolveError(
format!("Builtin module: {}", error),
Expand Down
36 changes: 1 addition & 35 deletions crates/rspack_error/src/diagnostic.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{backtrace::Backtrace, fmt};
use std::fmt;

use crate::{DiagnosticKind, Error, TraceableError};

Expand Down Expand Up @@ -92,8 +92,6 @@ impl Diagnostic {

impl From<Error> for Vec<Diagnostic> {
fn from(err: Error) -> Self {
let kind = err.kind();
let severity = err.severity();
let diagnostic = match err {
Error::InternalError(err) => Diagnostic {
message: err.error_message().to_string(),
Expand All @@ -103,18 +101,6 @@ impl From<Error> for Vec<Diagnostic> {
severity: err.severity(),
..Default::default()
},
Error::Napi {
status,
reason,
backtrace,
} => Diagnostic {
message: format!("Napi Error: {status} - {reason}\n{backtrace}"),
source_info: None,
start: 0,
end: 0,
severity: Severity::Error,
..Default::default()
},
Error::TraceableError(TraceableError {
start,
end,
Expand All @@ -137,26 +123,6 @@ impl From<Error> for Vec<Diagnostic> {
severity,
..Default::default()
},
Error::Io { source } => Diagnostic {
message: source.to_string(),
kind,
severity,
..Default::default()
},
Error::Anyhow { source } => Diagnostic {
kind,
severity,
message: {
let backtrace = match Backtrace::capture().status() {
std::backtrace::BacktraceStatus::Captured => {
format!("\nbacktrace:\n{}", source.backtrace())
}
_ => "".to_string(),
};
format!("{source}{backtrace}")
},
..Default::default()
},
Error::BatchErrors(diagnostics) => {
return diagnostics
.into_iter()
Expand Down
52 changes: 20 additions & 32 deletions crates/rspack_error/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
use std::{fmt, io, path::Path};

use miette::MietteDiagnostic;
use miette::{Diagnostic, MietteDiagnostic};
use rspack_util::swc::normalize_custom_filename;
use swc_core::common::SourceFile;
use thiserror::Error;

use crate::{internal_error, Severity};
use crate::Severity;

#[derive(Debug)]
pub struct InternalError(miette::Report);

impl<T: Diagnostic + Send + Sync + 'static> From<T> for InternalError {
fn from(value: T) -> Self {
InternalError(value.into())
}
}

impl InternalError {
pub fn new(error_message: String, severity: Severity) -> Self {
Self(miette::Report::new(
Expand Down Expand Up @@ -147,26 +154,13 @@ impl fmt::Display for TraceableError {
pub enum Error {
InternalError(InternalError),
TraceableError(TraceableError),
Io {
source: io::Error,
},
Anyhow {
source: anyhow::Error,
},
BatchErrors(Vec<Error>),
// for some reason, We could not just use `napi:Error` here
Napi {
status: String,
reason: String,
backtrace: String,
},
}

impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io { source, .. } => Some(source as &(dyn std::error::Error + 'static)),
Error::Anyhow { source, .. } => Some(source.as_ref()),
Error::InternalError(InternalError(i)) => i.source(),
_ => None,
}
}
Expand All @@ -177,8 +171,6 @@ impl fmt::Display for Error {
match self {
Error::InternalError(e) => write!(f, "{e}"),
Error::TraceableError(v) => write!(f, "{v}"),
Error::Io { source } => write!(f, "{source}"),
Error::Anyhow { source } => write!(f, "{source}"),
Error::BatchErrors(errs) => write!(
f,
"{}",
Expand All @@ -188,11 +180,6 @@ impl fmt::Display for Error {
.collect::<Vec<String>>()
.join("\n")
),
Error::Napi {
status,
reason,
backtrace,
} => write!(f, "napi error: {status} - {reason}\n{backtrace}"),
}
}
}
Expand All @@ -205,19 +192,19 @@ impl From<serde_json::Error> for Error {

impl From<io::Error> for Error {
fn from(source: io::Error) -> Self {
Error::Io { source }
Error::InternalError(DiagnosticError(source.into()).into())
}
}

impl From<anyhow::Error> for Error {
fn from(source: anyhow::Error) -> Self {
Error::Anyhow { source }
Error::InternalError(DiagnosticError(source.into()).into())
}
}

impl From<rspack_sources::Error> for Error {
fn from(value: rspack_sources::Error) -> Self {
internal_error!(value.to_string())
Error::InternalError(DiagnosticError(value.into()).into())
}
}

Expand All @@ -226,20 +213,14 @@ impl Error {
match self {
Error::InternalError(_) => DiagnosticKind::Internal,
Error::TraceableError(TraceableError { kind, .. }) => *kind,
Error::Io { .. } => DiagnosticKind::Io,
Error::Anyhow { .. } => DiagnosticKind::Internal,
Error::BatchErrors(_) => DiagnosticKind::Internal,
Error::Napi { .. } => DiagnosticKind::Internal,
}
}
pub fn severity(&self) -> Severity {
match self {
Error::InternalError(_) => Severity::Error,
Error::TraceableError(TraceableError { severity, .. }) => *severity,
Error::Io { .. } => Severity::Error,
Error::Anyhow { .. } => Severity::Error,
Error::BatchErrors(_) => Severity::Error,
Error::Napi { .. } => Severity::Error,
}
}
}
Expand Down Expand Up @@ -277,3 +258,10 @@ impl std::fmt::Display for DiagnosticKind {
}
}
}

/// Convenience [`Diagnostic`] that can be used as an "anonymous" wrapper for
/// Errors. This is intended to be paired with [`IntoDiagnostic`].
#[derive(Debug, Error)]
#[error(transparent)]
pub struct DiagnosticError(pub Box<dyn std::error::Error + Send + Sync + 'static>);
impl Diagnostic for DiagnosticError {}
2 changes: 1 addition & 1 deletion crates/rspack_fs/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl From<std::io::Error> for Error {
impl From<Error> for rspack_error::Error {
fn from(value: Error) -> Self {
match value {
Error::Io(err) => Self::Io { source: err },
Error::Io(err) => rspack_error::Error::from(err),
}
}
}
Expand Down
21 changes: 11 additions & 10 deletions crates/rspack_napi_shared/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
use std::{ffi::CString, ptr};

use napi::{bindgen_prelude::*, sys::napi_value, Env, Error, Result};
use rspack_error::{
miette::{self, Diagnostic},
thiserror::{self, Error},
};

#[derive(Debug, Error, Diagnostic)]
#[diagnostic(code(NapiError))]
#[error("Napi Error: {0}\n{1}")]
struct NodeError(String, String);

pub trait NapiErrorExt {
fn into_rspack_error(self) -> rspack_error::Error;
Expand All @@ -14,19 +23,11 @@ pub trait NapiResultExt<T> {

impl NapiErrorExt for Error {
fn into_rspack_error(self) -> rspack_error::Error {
rspack_error::Error::Napi {
status: format!("{}", self.status),
reason: self.reason,
backtrace: "".to_owned(),
}
rspack_error::Error::InternalError(NodeError(self.reason, "".to_string()).into())
}
fn into_rspack_error_with_detail(self, env: &Env) -> rspack_error::Error {
let (reason, backtrace) = extract_stack_or_message_from_napi_error(env, self);
rspack_error::Error::Napi {
status: Status::GenericFailure.to_string(),
reason,
backtrace: backtrace.unwrap_or_default(),
}
rspack_error::Error::InternalError(NodeError(reason, backtrace.unwrap_or_default()).into())
}
}

Expand Down

0 comments on commit 61772dc

Please sign in to comment.