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

refactor: rework error handling #878

Open
wants to merge 36 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
a5cda16
refactor: rework error handling
crowlKats Aug 21, 2024
9628c15
more error handling!
crowlKats Aug 22, 2024
58ebe99
cleanup
crowlKats Aug 22, 2024
baaae13
fix
crowlKats Aug 22, 2024
8afde02
fix
crowlKats Aug 22, 2024
2c2a538
rework moduleerror
crowlKats Aug 23, 2024
e947204
fixes
crowlKats Aug 23, 2024
6380ef9
fixes
crowlKats Aug 24, 2024
b44cac1
fixes
crowlKats Aug 24, 2024
bc6d787
Merge branch 'main' into error-rework
crowlKats Aug 24, 2024
537f821
fixes
crowlKats Aug 26, 2024
970b5c8
fmt
crowlKats Aug 26, 2024
5fb5e0b
lints
crowlKats Aug 26, 2024
6483eb8
fix
crowlKats Aug 26, 2024
eb9d8e0
lints
crowlKats Aug 26, 2024
e21ce6f
fmt
crowlKats Aug 26, 2024
f8c5f2b
lint
crowlKats Aug 26, 2024
e00c1de
fix
crowlKats Aug 26, 2024
12e735f
add get_additional_properties
crowlKats Aug 27, 2024
5edf11c
clean up
crowlKats Aug 28, 2024
873991b
fmt
crowlKats Aug 28, 2024
0d4e7a1
lint
crowlKats Aug 28, 2024
c5f85ad
Merge branch 'main' into error-rework
crowlKats Oct 12, 2024
0f192a1
fix
crowlKats Oct 14, 2024
5215557
Merge branch 'main' into error-rework
crowlKats Oct 14, 2024
1964f39
fix
crowlKats Oct 14, 2024
4b7d31a
cleanip and fixes
crowlKats Oct 18, 2024
d6e0011
more cleanup
crowlKats Oct 19, 2024
2011f2b
Merge branch 'main' into error-rework
crowlKats Oct 19, 2024
8ed6ef3
lint
crowlKats Oct 19, 2024
fbada7f
fix
crowlKats Oct 20, 2024
74d993c
fix
crowlKats Oct 20, 2024
4ed073a
fix
crowlKats Oct 20, 2024
f293421
update test
crowlKats Oct 20, 2024
abdf961
unnecessary_wraps
crowlKats Oct 22, 2024
73955f7
fixes and cleanup
crowlKats Oct 22, 2024
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
22 changes: 18 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::JsNativeError;
use deno_core::Extension;
use deno_core::JsRuntime;
use deno_core::JsRuntimeForSnapshot;
Expand Down Expand Up @@ -49,10 +49,22 @@ 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"
);

deno_core::js_error_wrapper!(
deno_ast::TranspileError,
JsTranspileError,
"TypeError"
);

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

let parsed = deno_ast::parse_module(ParseParams {
Expand All @@ -62,7 +74,8 @@ pub fn maybe_transpile_source(
capture_tokens: false,
scope_analysis: false,
maybe_syntax: None,
})?;
})
.map_err(|e| JsNativeError::from_err(JsParseDiagnostic(e)))?;
let transpiled_source = parsed
.transpile(
&deno_ast::TranspileOptions {
Expand All @@ -74,7 +87,8 @@ pub fn maybe_transpile_source(
inline_sources: true,
..Default::default()
},
)?
)
.map_err(|e| JsNativeError::from_err(JsTranspileError(e)))?
.into_source();
Ok((
String::from_utf8(transpiled_source.source).unwrap().into(),
Expand Down
29 changes: 15 additions & 14 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 All @@ -264,7 +265,7 @@ impl<'a> ToV8<'a> for bool {
}

impl<'a> FromV8<'a> for bool {
type Error = StdAnyError;
type Error = JsNativeError;
#[inline]
fn from_v8(
_scope: &mut v8::HandleScope<'a>,
Expand All @@ -273,6 +274,6 @@ impl<'a> FromV8<'a> for bool {
value
.try_cast::<v8::Boolean>()
.map(|v| v.is_true())
.map_err(|_| crate::error::type_error("Expected boolean").into())
.map_err(|_| JsNativeError::type_error("Expected boolean"))
}
}
Loading
Loading