Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] refactor: rework error handling #878

Open
wants to merge 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions core/00_infra.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,11 @@
const err = errorBuilder ? errorBuilder(res.message) : new Error(
`Unregistered error class: "${className}"\n ${res.message}\n Classes of errors returned from ops should be registered via Deno.core.registerErrorClass().`,
);
// Set .code if error was a known OS error, see error_codes.rs
if (res.code) {
err.code = res.code;

if (res.additional_properties) {
for (const [key, value] of res.additional_properties) {
res[key] = value;
}
}
// Strip eventLoopTick() calls from stack trace
ErrorCaptureStackTrace(err, eventLoopTick);
Expand Down
1 change: 1 addition & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ static_assertions.workspace = true
tokio.workspace = true
url.workspace = true
v8.workspace = true
thiserror = "1.0.60"

[dev-dependencies]
bencher.workspace = true
Expand Down
28 changes: 23 additions & 5 deletions core/async_cancel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ use std::io;
use std::pin::Pin;
use std::rc::Rc;

use crate::error::JsErrorClass;
use crate::RcLike;
use crate::Resource;
use futures::future::FusedFuture;
use futures::future::Future;
use futures::future::TryFuture;
use futures::task::Context;
use futures::task::Poll;
use pin_project::pin_project;

use crate::RcLike;
use crate::Resource;

use self::internal as i;

#[derive(Debug, Default)]
Expand Down Expand Up @@ -242,6 +242,25 @@ impl From<Canceled> for io::Error {
}
}

impl JsErrorClass for Canceled {
fn get_class(&self) -> &'static str {
let io_err: io::Error = self.to_owned().into();
io_err.get_class()
}

fn get_message(&self) -> Cow<'static, str> {
let io_err: io::Error = self.to_owned().into();
io_err.get_message()
}

fn get_additional_properties(
&self,
) -> Option<Vec<(Cow<'static, str>, Cow<'static, str>)>> {
let io_err: io::Error = self.to_owned().into();
io_err.get_additional_properties()
}
}

mod internal {
use super::Abortable;
use super::CancelHandle;
Expand Down Expand Up @@ -666,7 +685,6 @@ mod internal {
#[cfg(test)]
mod tests {
use super::*;
use anyhow::Error;
use futures::future::pending;
use futures::future::poll_fn;
use futures::future::ready;
Expand Down Expand Up @@ -782,7 +800,7 @@ mod tests {
// Cancel a spawned task before it actually runs.
let cancel_handle = Rc::new(CancelHandle::new());
let future = spawn(async { panic!("the task should not be spawned") })
.map_err(Error::from)
.map_err(anyhow::Error::from)
.try_or_cancel(&cancel_handle);
cancel_handle.cancel();
let error = future.await.unwrap_err();
Expand Down
4 changes: 2 additions & 2 deletions core/benches/ops/async.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use bencher::*;
use deno_core::error::generic_error;
use deno_core::error::JsNativeError;
use deno_core::*;
use std::ffi::c_void;
use tokio::runtime::Runtime;
Expand Down Expand Up @@ -118,7 +118,7 @@ fn bench_op(
..Default::default()
});
let err_mapper =
|err| generic_error(format!("{op} test failed ({call}): {err:?}"));
|err| JsNativeError::generic(format!("{op} test failed ({call}): {err:?}"));

let args = (0..arg_count)
.map(|n| format!("arg{n}"))
Expand Down
6 changes: 3 additions & 3 deletions core/benches/ops/sync.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
#![allow(deprecated)]
use bencher::*;
use deno_core::error::generic_error;
use deno_core::*;
use std::borrow::Cow;
use std::ffi::c_void;
Expand Down Expand Up @@ -183,8 +182,9 @@ fn bench_op(
})),
..Default::default()
});
let err_mapper =
|err| generic_error(format!("{op} test failed ({call}): {err:?}"));
let err_mapper = |err| {
error::JsNativeError::generic(format!("{op} test failed ({call}): {err:?}"))
};

let args = (0..arg_count)
.map(|n| format!("arg{n}"))
Expand Down
16 changes: 12 additions & 4 deletions core/benches/snapshot/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use criterion::*;
use deno_ast::MediaType;
use deno_ast::ParseParams;
use deno_ast::SourceMapOption;
use deno_core::error::AnyError;
use deno_core::error::JsErrorClass;
use deno_core::Extension;
use deno_core::JsRuntime;
use deno_core::JsRuntimeForSnapshot;
Expand Down Expand Up @@ -49,10 +49,16 @@ fn make_extensions_ops() -> Vec<Extension> {
fake_extensions!(init_ops, a, b, c, d, e, f, g, h, i, j, k, l, m, n)
}

deno_core::js_error_wrapper!(
deno_ast::ParseDiagnostic,
JsParseDiagnostic,
"TypeError"
);

pub fn maybe_transpile_source(
specifier: ModuleName,
source: ModuleCodeString,
) -> Result<(ModuleCodeString, Option<SourceMapData>), AnyError> {
) -> Result<(ModuleCodeString, Option<SourceMapData>), Box<dyn JsErrorClass>> {
let media_type = MediaType::TypeScript;

let parsed = deno_ast::parse_module(ParseParams {
Expand All @@ -62,7 +68,8 @@ pub fn maybe_transpile_source(
capture_tokens: false,
scope_analysis: false,
maybe_syntax: None,
})?;
})
.map_err(JsParseDiagnostic)?;
let transpiled_source = parsed
.transpile(
&deno_ast::TranspileOptions {
Expand All @@ -74,7 +81,8 @@ pub fn maybe_transpile_source(
inline_sources: true,
..Default::default()
},
)?
)
.map_err(anyhow::Error::new)?
.into_source();
Ok((
String::from_utf8(transpiled_source.source).unwrap().into(),
Expand Down
25 changes: 13 additions & 12 deletions core/convert.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

use crate::error::StdAnyError;
use crate::error::JsNativeError;
use crate::runtime::ops;
use std::convert::Infallible;

Expand Down Expand Up @@ -87,15 +87,16 @@ pub trait ToV8<'a> {
///
/// ```ignore
/// use deno_core::FromV8;
/// use deno_core::error::JsNativeError;
/// use deno_core::convert::Smi;
/// use deno_core::op2;
///
/// struct Foo(i32);
///
/// impl<'a> FromV8<'a> for Foo {
/// // This conversion can fail, so we use `deno_core::error::StdAnyError` as the error type.
/// // This conversion can fail, so we use `JsNativeError` as the error type.
/// // Any error type that implements `std::error::Error` can be used here.
/// type Error = deno_core::error::StdAnyError;
/// type Error = JsNativeError;
///
/// fn from_v8(scope: &mut v8::HandleScope<'a>, value: v8::Local<'a, v8::Value>) -> Result<Self, Self::Error> {
/// /// We expect this value to be a `v8::Integer`, so we use the [`Smi`][deno_core::convert::Smi] wrapper type to convert it.
Expand All @@ -122,7 +123,7 @@ pub trait FromV8<'a>: Sized {
// impls

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// Marks a numeric type as being serialized as a v8 `smi` in a `v8::Integer`.
/// Marks a numeric type as being serialized as a v8 `smi` in a `v8::Integer`.
#[repr(transparent)]
pub struct Smi<T: SmallInt>(pub T);

Expand Down Expand Up @@ -170,22 +171,22 @@ impl<'a, T: SmallInt> ToV8<'a> for Smi<T> {
}

impl<'a, T: SmallInt> FromV8<'a> for Smi<T> {
type Error = StdAnyError;
type Error = JsNativeError;

#[inline]
fn from_v8(
_scope: &mut v8::HandleScope<'a>,
value: v8::Local<'a, v8::Value>,
) -> Result<Self, Self::Error> {
let v = crate::runtime::ops::to_i32_option(&value).ok_or_else(|| {
crate::error::type_error(format!("Expected {}", T::NAME))
let v = ops::to_i32_option(&value).ok_or_else(|| {
JsNativeError::type_error(format!("Expected {}", T::NAME))
})?;
Ok(Smi(T::from_i32(v)))
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// Marks a numeric type as being serialized as a v8 `number` in a `v8::Number`.
/// Marks a numeric type as being serialized as a v8 `number` in a `v8::Number`.
#[repr(transparent)]
pub struct Number<T: Numeric>(pub T);

Expand Down Expand Up @@ -240,15 +241,15 @@ impl<'a, T: Numeric> ToV8<'a> for Number<T> {
}

impl<'a, T: Numeric> FromV8<'a> for Number<T> {
type Error = StdAnyError;
type Error = JsNativeError;
#[inline]
fn from_v8(
_scope: &mut v8::HandleScope<'a>,
value: v8::Local<'a, v8::Value>,
) -> Result<Self, Self::Error> {
T::from_value(&value).map(Number).ok_or_else(|| {
crate::error::type_error(format!("Expected {}", T::NAME)).into()
})
T::from_value(&value)
.map(Number)
.ok_or_else(|| JsNativeError::type_error(format!("Expected {}", T::NAME)))
}
}

Expand Down
Loading