1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-21 15:04:11 -05:00

refactor: use the 'anyhow' crate instead of 'ErrBox' (#7476)

This commit is contained in:
Bert Belder 2020-09-14 18:48:57 +02:00
parent 3da20d19a1
commit f5b40c918c
No known key found for this signature in database
GPG key ID: 7A77887B2E2ED461
63 changed files with 898 additions and 861 deletions

7
Cargo.lock generated
View file

@ -58,6 +58,12 @@ dependencies = [
"winapi 0.3.9",
]
[[package]]
name = "anyhow"
version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b602bfe940d21c130f3895acd65221e8a61270debe89d628b9cb4e3ccb8569b"
[[package]]
name = "anymap"
version = "0.12.1"
@ -450,6 +456,7 @@ dependencies = [
name = "deno_core"
version = "0.57.0"
dependencies = [
"anyhow",
"downcast-rs",
"futures",
"indexmap",

View file

@ -1,8 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use crate::msg::MediaType;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use deno_core::ModuleSpecifier;
use std::error::Error;
use std::fmt;
@ -43,7 +42,7 @@ use swc_ecmascript::transforms::react;
use swc_ecmascript::transforms::typescript;
use swc_ecmascript::visit::FoldWith;
type Result<V> = result::Result<V, ErrBox>;
type Result<V> = result::Result<V, AnyError>;
static TARGET: JscTarget = JscTarget::Es2020;
@ -357,9 +356,9 @@ pub fn parse(
let mut diagnostic = err.into_diagnostic(&handler);
diagnostic.emit();
ErrBox::from(DiagnosticBuffer::from_error_buffer(error_buffer, |span| {
DiagnosticBuffer::from_error_buffer(error_buffer, |span| {
sm.lookup_char_pos(span.lo)
}))
})
})?;
let leading_comments =
comments.with_leading(module.span.lo, |comments| comments.to_vec());

View file

@ -5,8 +5,9 @@ use crate::file_fetcher::SourceFile;
use crate::global_state::GlobalState;
use crate::inspector::DenoInspector;
use crate::permissions::Permissions;
use deno_core::error::generic_error;
use deno_core::error::AnyError;
use deno_core::v8;
use deno_core::ErrBox;
use deno_core::ModuleSpecifier;
use serde::Deserialize;
use std::collections::VecDeque;
@ -85,7 +86,7 @@ impl CoverageCollector {
})
}
async fn dispatch(&mut self, message: String) -> Result<String, ErrBox> {
async fn dispatch(&mut self, message: String) -> Result<String, AnyError> {
let message = v8::inspector::StringView::from(message.as_bytes());
self.v8_session.dispatch_protocol_message(message);
@ -93,7 +94,7 @@ impl CoverageCollector {
Ok(response.unwrap())
}
pub async fn start_collecting(&mut self) -> Result<(), ErrBox> {
pub async fn start_collecting(&mut self) -> Result<(), AnyError> {
self
.dispatch(r#"{"id":1,"method":"Runtime.enable"}"#.into())
.await?;
@ -110,7 +111,7 @@ impl CoverageCollector {
pub async fn take_precise_coverage(
&mut self,
) -> Result<Vec<ScriptCoverage>, ErrBox> {
) -> Result<Vec<ScriptCoverage>, AnyError> {
let response = self
.dispatch(r#"{"id":4,"method":"Profiler.takePreciseCoverage" }"#.into())
.await?;
@ -121,7 +122,7 @@ impl CoverageCollector {
Ok(coverage_result.result.result)
}
pub async fn stop_collecting(&mut self) -> Result<(), ErrBox> {
pub async fn stop_collecting(&mut self) -> Result<(), AnyError> {
self
.dispatch(r#"{"id":5,"method":"Profiler.stopPreciseCoverage"}"#.into())
.await?;
@ -220,7 +221,7 @@ impl PrettyCoverageReporter {
.global_state
.file_fetcher
.fetch_cached_source_file(&module_specifier, Permissions::allow_all())
.ok_or_else(|| ErrBox::error("unable to fetch source file"))
.ok_or_else(|| generic_error("unable to fetch source file"))
})
.ok();

View file

@ -1,18 +1,18 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
//! There are many types of errors in Deno:
//! - ErrBox: a generic boxed object. This is the super type of all
//! errors handled in Rust.
//! - AnyError: a generic wrapper that can encapsulate any type of error.
//! - JsError: a container for the error message and stack trace for exceptions
//! thrown in JavaScript code. We use this to pretty-print stack traces.
//! - Diagnostic: these are errors that originate in TypeScript's compiler.
//! They're similar to JsError, in that they have line numbers.
//! But Diagnostics are compile-time type errors, whereas JsErrors are runtime
//! They're similar to JsError, in that they have line numbers. But
//! Diagnostics are compile-time type errors, whereas JsErrors are runtime
//! exceptions.
use crate::ast::DiagnosticBuffer;
use crate::import_map::ImportMapError;
use deno_core::ErrBox;
use deno_core::error::get_custom_error_class;
use deno_core::error::AnyError;
use deno_core::ModuleResolutionError;
use rustyline::error::ReadlineError;
use std::env;
@ -170,63 +170,59 @@ fn get_nix_error_class(error: &nix::Error) -> &'static str {
}
}
pub(crate) fn get_error_class_name(e: &ErrBox) -> &'static str {
use ErrBox::*;
match e {
Simple { class, .. } => Some(*class),
_ => None,
}
.or_else(|| {
e.downcast_ref::<dlopen::Error>()
.map(get_dlopen_error_class)
})
.or_else(|| {
e.downcast_ref::<env::VarError>()
.map(get_env_var_error_class)
})
.or_else(|| {
e.downcast_ref::<ImportMapError>()
.map(get_import_map_error_class)
})
.or_else(|| e.downcast_ref::<io::Error>().map(get_io_error_class))
.or_else(|| {
e.downcast_ref::<ModuleResolutionError>()
.map(get_module_resolution_error_class)
})
.or_else(|| {
e.downcast_ref::<notify::Error>()
.map(get_notify_error_class)
})
.or_else(|| {
e.downcast_ref::<ReadlineError>()
.map(get_readline_error_class)
})
.or_else(|| {
e.downcast_ref::<reqwest::Error>()
.map(get_request_error_class)
})
.or_else(|| e.downcast_ref::<regex::Error>().map(get_regex_error_class))
.or_else(|| {
e.downcast_ref::<serde_json::error::Error>()
.map(get_serde_json_error_class)
})
.or_else(|| {
e.downcast_ref::<DiagnosticBuffer>()
.map(get_diagnostic_class)
})
.or_else(|| {
e.downcast_ref::<url::ParseError>()
.map(get_url_parse_error_class)
})
.or_else(|| {
#[cfg(unix)]
let maybe_get_nix_error_class =
|| e.downcast_ref::<nix::Error>().map(get_nix_error_class);
#[cfg(not(unix))]
let maybe_get_nix_error_class = || Option::<&'static str>::None;
(maybe_get_nix_error_class)()
})
.unwrap_or_else(|| {
panic!("ErrBox '{}' contains boxed error of unknown type", e);
})
pub(crate) fn get_error_class_name(e: &AnyError) -> &'static str {
get_custom_error_class(e)
.or_else(|| {
e.downcast_ref::<dlopen::Error>()
.map(get_dlopen_error_class)
})
.or_else(|| {
e.downcast_ref::<env::VarError>()
.map(get_env_var_error_class)
})
.or_else(|| {
e.downcast_ref::<ImportMapError>()
.map(get_import_map_error_class)
})
.or_else(|| e.downcast_ref::<io::Error>().map(get_io_error_class))
.or_else(|| {
e.downcast_ref::<ModuleResolutionError>()
.map(get_module_resolution_error_class)
})
.or_else(|| {
e.downcast_ref::<notify::Error>()
.map(get_notify_error_class)
})
.or_else(|| {
e.downcast_ref::<ReadlineError>()
.map(get_readline_error_class)
})
.or_else(|| {
e.downcast_ref::<reqwest::Error>()
.map(get_request_error_class)
})
.or_else(|| e.downcast_ref::<regex::Error>().map(get_regex_error_class))
.or_else(|| {
e.downcast_ref::<serde_json::error::Error>()
.map(get_serde_json_error_class)
})
.or_else(|| {
e.downcast_ref::<DiagnosticBuffer>()
.map(get_diagnostic_class)
})
.or_else(|| {
e.downcast_ref::<url::ParseError>()
.map(get_url_parse_error_class)
})
.or_else(|| {
#[cfg(unix)]
let maybe_get_nix_error_class =
|| e.downcast_ref::<nix::Error>().map(get_nix_error_class);
#[cfg(not(unix))]
let maybe_get_nix_error_class = || Option::<&'static str>::None;
(maybe_get_nix_error_class)()
})
.unwrap_or_else(|| {
panic!("Error '{}' contains boxed error of unknown type", e);
})
}

View file

@ -8,7 +8,10 @@ use crate::http_util::FetchOnceResult;
use crate::msg;
use crate::permissions::Permissions;
use crate::text_encoding;
use deno_core::ErrBox;
use deno_core::error::custom_error;
use deno_core::error::generic_error;
use deno_core::error::uri_error;
use deno_core::error::AnyError;
use deno_core::ModuleSpecifier;
use futures::future::FutureExt;
use log::info;
@ -122,7 +125,7 @@ impl SourceFileFetcher {
no_remote: bool,
cached_only: bool,
ca_file: Option<&str>,
) -> Result<Self, ErrBox> {
) -> Result<Self, AnyError> {
let file_fetcher = Self {
http_cache,
source_file_cache: SourceFileCache::default(),
@ -136,9 +139,9 @@ impl SourceFileFetcher {
Ok(file_fetcher)
}
pub fn check_if_supported_scheme(url: &Url) -> Result<(), ErrBox> {
pub fn check_if_supported_scheme(url: &Url) -> Result<(), AnyError> {
if !SUPPORTED_URL_SCHEMES.contains(&url.scheme()) {
return Err(ErrBox::error(format!(
return Err(generic_error(format!(
"Unsupported scheme \"{}\" for module \"{}\". Supported schemes: {:#?}",
url.scheme(),
url,
@ -179,7 +182,7 @@ impl SourceFileFetcher {
/// Save a given source file into cache.
/// Allows injection of files that normally would not present
/// in filesystem.
/// This is useful when e.g. TS compiler retrieves a custom file
/// This is useful when e.g. TS compiler retrieves a custom_error file
/// under a dummy specifier.
pub fn save_source_file_in_cache(
&self,
@ -194,7 +197,7 @@ impl SourceFileFetcher {
specifier: &ModuleSpecifier,
maybe_referrer: Option<ModuleSpecifier>,
permissions: Permissions,
) -> Result<SourceFile, ErrBox> {
) -> Result<SourceFile, AnyError> {
let module_url = specifier.as_url().to_owned();
debug!(
"fetch_source_file specifier: {} maybe_referrer: {:#?}",
@ -256,13 +259,13 @@ impl SourceFileFetcher {
r#"Cannot find module "{}"{} in cache, --cached-only is specified"#,
module_url, referrer_suffix
);
ErrBox::new("NotFound", msg)
custom_error("NotFound", msg)
} else if is_not_found {
let msg = format!(
r#"Cannot resolve module "{}"{}"#,
module_url, referrer_suffix
);
ErrBox::new("NotFound", msg)
custom_error("NotFound", msg)
} else {
err
};
@ -275,7 +278,7 @@ impl SourceFileFetcher {
&self,
module_url: &Url,
permissions: &Permissions,
) -> Result<Option<SourceFile>, ErrBox> {
) -> Result<Option<SourceFile>, AnyError> {
let url_scheme = module_url.scheme();
let is_local_file = url_scheme == "file";
SourceFileFetcher::check_if_supported_scheme(&module_url)?;
@ -306,7 +309,7 @@ impl SourceFileFetcher {
no_remote: bool,
cached_only: bool,
permissions: &Permissions,
) -> Result<SourceFile, ErrBox> {
) -> Result<SourceFile, AnyError> {
let url_scheme = module_url.scheme();
let is_local_file = url_scheme == "file";
SourceFileFetcher::check_if_supported_scheme(&module_url)?;
@ -345,10 +348,10 @@ impl SourceFileFetcher {
&self,
module_url: &Url,
permissions: &Permissions,
) -> Result<SourceFile, ErrBox> {
let filepath = module_url.to_file_path().map_err(|()| {
ErrBox::new("URIError", "File URL contains invalid path")
})?;
) -> Result<SourceFile, AnyError> {
let filepath = module_url
.to_file_path()
.map_err(|()| uri_error("File URL contains invalid path"))?;
permissions.check_read(&filepath)?;
let source_code = match fs::read(filepath.clone()) {
@ -382,9 +385,9 @@ impl SourceFileFetcher {
&self,
module_url: &Url,
redirect_limit: i64,
) -> Result<Option<SourceFile>, ErrBox> {
) -> Result<Option<SourceFile>, AnyError> {
if redirect_limit < 0 {
return Err(ErrBox::new("Http", "too many redirects"));
return Err(custom_error("Http", "too many redirects"));
}
let result = self.http_cache.get(&module_url);
@ -447,9 +450,9 @@ impl SourceFileFetcher {
cached_only: bool,
redirect_limit: i64,
permissions: &Permissions,
) -> Pin<Box<dyn Future<Output = Result<SourceFile, ErrBox>>>> {
) -> Pin<Box<dyn Future<Output = Result<SourceFile, AnyError>>>> {
if redirect_limit < 0 {
let e = ErrBox::new("Http", "too many redirects");
let e = custom_error("Http", "too many redirects");
return futures::future::err(e).boxed_local();
}
@ -481,7 +484,7 @@ impl SourceFileFetcher {
"Cannot find remote file '{}' in cache, --cached-only is specified",
module_url
);
return futures::future::err(ErrBox::new("NotFound", message))
return futures::future::err(custom_error("NotFound", message))
.boxed_local();
}

View file

@ -1,5 +1,5 @@
use crate::colors;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use futures::stream::StreamExt;
use futures::Future;
use notify::event::Event as NotifyEvent;
@ -15,8 +15,7 @@ use tokio::select;
use tokio::sync::mpsc;
// TODO(bartlomieju): rename
type WatchFuture =
Pin<Box<dyn Future<Output = std::result::Result<(), deno_core::ErrBox>>>>;
type WatchFuture = Pin<Box<dyn Future<Output = Result<(), AnyError>>>>;
async fn error_handler(watch_future: WatchFuture) {
let result = watch_future.await;
@ -29,7 +28,7 @@ async fn error_handler(watch_future: WatchFuture) {
pub async fn watch_func<F>(
watch_paths: &[PathBuf],
closure: F,
) -> Result<(), ErrBox>
) -> Result<(), AnyError>
where
F: Fn() -> WatchFuture,
{
@ -60,13 +59,14 @@ where
}
}
pub async fn file_watcher(paths: &[PathBuf]) -> Result<(), deno_core::ErrBox> {
let (sender, mut receiver) = mpsc::channel::<Result<NotifyEvent, ErrBox>>(16);
pub async fn file_watcher(paths: &[PathBuf]) -> Result<(), AnyError> {
let (sender, mut receiver) =
mpsc::channel::<Result<NotifyEvent, AnyError>>(16);
let sender = std::sync::Mutex::new(sender);
let mut watcher: RecommendedWatcher =
Watcher::new_immediate(move |res: Result<NotifyEvent, NotifyError>| {
let res2 = res.map_err(ErrBox::from);
let res2 = res.map_err(AnyError::from);
let mut sender = sender.lock().unwrap();
// Ignore result, if send failed it means that watcher was already closed,
// but not all messages have been flushed.

View file

@ -11,7 +11,8 @@ use crate::colors;
use crate::diff::diff;
use crate::fs::files_in_subtree;
use crate::text_encoding;
use deno_core::ErrBox;
use deno_core::error::generic_error;
use deno_core::error::AnyError;
use dprint_plugin_typescript as dprint;
use std::fs;
use std::io::stdin;
@ -33,7 +34,7 @@ pub async fn format(
args: Vec<String>,
check: bool,
exclude: Vec<String>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
if args.len() == 1 && args[0] == "-" {
return format_stdin(check);
}
@ -56,7 +57,7 @@ pub async fn format(
async fn check_source_files(
config: dprint::configuration::Configuration,
paths: Vec<PathBuf>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let not_formatted_files_count = Arc::new(AtomicUsize::new(0));
let checked_files_count = Arc::new(AtomicUsize::new(0));
@ -116,7 +117,7 @@ async fn check_source_files(
Ok(())
} else {
let not_formatted_files_str = files_str(not_formatted_files_count);
Err(ErrBox::error(format!(
Err(generic_error(format!(
"Found {} not formatted {} in {}",
not_formatted_files_count, not_formatted_files_str, checked_files_str,
)))
@ -126,7 +127,7 @@ async fn check_source_files(
async fn format_source_files(
config: dprint::configuration::Configuration,
paths: Vec<PathBuf>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let formatted_files_count = Arc::new(AtomicUsize::new(0));
let checked_files_count = Arc::new(AtomicUsize::new(0));
let output_lock = Arc::new(Mutex::new(0)); // prevent threads outputting at the same time
@ -184,10 +185,10 @@ async fn format_source_files(
/// Format stdin and write result to stdout.
/// Treats input as TypeScript.
/// Compatible with `--check` flag.
fn format_stdin(check: bool) -> Result<(), ErrBox> {
fn format_stdin(check: bool) -> Result<(), AnyError> {
let mut source = String::new();
if stdin().read_to_string(&mut source).is_err() {
return Err(ErrBox::error("Failed to read from stdin"));
return Err(generic_error("Failed to read from stdin"));
}
let config = get_config();
@ -203,7 +204,7 @@ fn format_stdin(check: bool) -> Result<(), ErrBox> {
}
}
Err(e) => {
return Err(ErrBox::error(e));
return Err(generic_error(e));
}
}
Ok(())
@ -261,7 +262,7 @@ struct FileContents {
had_bom: bool,
}
fn read_file_contents(file_path: &Path) -> Result<FileContents, ErrBox> {
fn read_file_contents(file_path: &Path) -> Result<FileContents, AnyError> {
let file_bytes = fs::read(&file_path)?;
let charset = text_encoding::detect_charset(&file_bytes);
let file_text = text_encoding::convert_to_utf8(&file_bytes, charset)?;
@ -279,7 +280,7 @@ fn read_file_contents(file_path: &Path) -> Result<FileContents, ErrBox> {
fn write_file_contents(
file_path: &Path,
file_contents: FileContents,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let file_text = if file_contents.had_bom {
// add back the BOM
format!("{}{}", BOM_CHAR, file_contents.text)
@ -293,9 +294,9 @@ fn write_file_contents(
pub async fn run_parallelized<F>(
file_paths: Vec<PathBuf>,
f: F,
) -> Result<(), ErrBox>
) -> Result<(), AnyError>
where
F: FnOnce(PathBuf) -> Result<(), ErrBox> + Send + 'static + Clone,
F: FnOnce(PathBuf) -> Result<(), AnyError> + Send + 'static + Clone,
{
let handles = file_paths.iter().map(|file_path| {
let f = f.clone();

View file

@ -3,7 +3,8 @@
use crate::colors;
use crate::source_maps::apply_source_map;
use crate::source_maps::SourceMapGetter;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use deno_core::error::JsError as CoreJsError;
use std::error::Error;
use std::fmt;
use std::ops::Deref;
@ -105,13 +106,13 @@ fn format_maybe_source_line(
/// Wrapper around deno_core::JsError which provides color to_string.
#[derive(Debug)]
pub struct JsError(deno_core::JsError);
pub struct JsError(CoreJsError);
impl JsError {
pub fn create(
core_js_error: deno_core::JsError,
core_js_error: CoreJsError,
source_map_getter: &impl SourceMapGetter,
) -> ErrBox {
) -> AnyError {
let core_js_error = apply_source_map(&core_js_error, source_map_getter);
let js_error = Self(core_js_error);
js_error.into()
@ -119,7 +120,7 @@ impl JsError {
}
impl Deref for JsError {
type Target = deno_core::JsError;
type Target = CoreJsError;
fn deref(&self) -> &Self::Target {
&self.0
}

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::error::AnyError;
pub use deno_core::normalize_path;
use deno_core::ErrBox;
use std::env::current_dir;
use std::fs::OpenOptions;
use std::io::Write;
@ -47,7 +47,7 @@ pub fn write_file_2<T: AsRef<[u8]>>(
file.write_all(data.as_ref())
}
pub fn resolve_from_cwd(path: &Path) -> Result<PathBuf, ErrBox> {
pub fn resolve_from_cwd(path: &Path) -> Result<PathBuf, AnyError> {
let resolved_path = if path.is_absolute() {
path.to_owned()
} else {

View file

@ -15,7 +15,7 @@ use crate::state::exit_unstable;
use crate::tsc::CompiledModule;
use crate::tsc::TargetLib;
use crate::tsc::TsCompiler;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use deno_core::ModuleSpecifier;
use std::env;
use std::sync::atomic::AtomicUsize;
@ -41,7 +41,7 @@ pub struct GlobalState {
}
impl GlobalState {
pub fn new(flags: flags::Flags) -> Result<Arc<Self>, ErrBox> {
pub fn new(flags: flags::Flags) -> Result<Arc<Self>, AnyError> {
let custom_root = env::var("DENO_DIR").map(String::into).ok();
let dir = deno_dir::DenoDir::new(custom_root)?;
let deps_cache_location = dir.root.join("deps");
@ -107,7 +107,7 @@ impl GlobalState {
permissions: Permissions,
is_dyn_import: bool,
maybe_import_map: Option<ImportMap>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let module_specifier = module_specifier.clone();
// TODO(ry) Try to lift compile_lock as high up in the call stack for
@ -188,7 +188,7 @@ impl GlobalState {
&self,
module_specifier: ModuleSpecifier,
_maybe_referrer: Option<ModuleSpecifier>,
) -> Result<CompiledModule, ErrBox> {
) -> Result<CompiledModule, AnyError> {
let module_specifier = module_specifier.clone();
let out = self

View file

@ -6,7 +6,7 @@
/// at hand.
use crate::fs as deno_fs;
use crate::http_util::HeadersMap;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use serde::Serialize;
use serde_derive::Deserialize;
use std::fs;
@ -81,14 +81,14 @@ pub struct Metadata {
}
impl Metadata {
pub fn write(&self, cache_filename: &Path) -> Result<(), ErrBox> {
pub fn write(&self, cache_filename: &Path) -> Result<(), AnyError> {
let metadata_filename = Self::filename(cache_filename);
let json = serde_json::to_string_pretty(self)?;
deno_fs::write_file(&metadata_filename, json, 0o666)?;
Ok(())
}
pub fn read(cache_filename: &Path) -> Result<Metadata, ErrBox> {
pub fn read(cache_filename: &Path) -> Result<Metadata, AnyError> {
let metadata_filename = Metadata::filename(&cache_filename);
let metadata = fs::read_to_string(metadata_filename)?;
let metadata: Metadata = serde_json::from_str(&metadata)?;
@ -135,7 +135,7 @@ impl HttpCache {
// TODO(bartlomieju): this method should check headers file
// and validate against ETAG/Last-modified-as headers.
// ETAG check is currently done in `cli/file_fetcher.rs`.
pub fn get(&self, url: &Url) -> Result<(File, HeadersMap), ErrBox> {
pub fn get(&self, url: &Url) -> Result<(File, HeadersMap), AnyError> {
let cache_filename = self.location.join(url_to_filename(url));
let metadata_filename = Metadata::filename(&cache_filename);
let file = File::open(cache_filename)?;
@ -144,7 +144,7 @@ impl HttpCache {
Ok((file, metadata.headers))
}
pub fn get_metadata(&self, url: &Url) -> Result<Metadata, ErrBox> {
pub fn get_metadata(&self, url: &Url) -> Result<Metadata, AnyError> {
let cache_filename = self.location.join(url_to_filename(url));
let metadata_filename = Metadata::filename(&cache_filename);
let metadata = fs::read_to_string(metadata_filename)?;
@ -157,7 +157,7 @@ impl HttpCache {
url: &Url,
headers_map: HeadersMap,
content: &[u8],
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let cache_filename = self.location.join(url_to_filename(url));
// Create parent directory
let parent_filename = cache_filename

View file

@ -2,7 +2,8 @@
use crate::version;
use bytes::Bytes;
use deno_core::ErrBox;
use deno_core::error::generic_error;
use deno_core::error::AnyError;
use reqwest::header::HeaderMap;
use reqwest::header::HeaderValue;
use reqwest::header::IF_NONE_MATCH;
@ -26,7 +27,7 @@ use url::Url;
/// Create new instance of async reqwest::Client. This client supports
/// proxies and doesn't follow redirects.
pub fn create_http_client(ca_file: Option<&str>) -> Result<Client, ErrBox> {
pub fn create_http_client(ca_file: Option<&str>) -> Result<Client, AnyError> {
let mut headers = HeaderMap::new();
headers.insert(
USER_AGENT,
@ -46,7 +47,7 @@ pub fn create_http_client(ca_file: Option<&str>) -> Result<Client, ErrBox> {
builder
.build()
.map_err(|_| ErrBox::error("Unable to build http client"))
.map_err(|_| generic_error("Unable to build http client"))
}
/// Construct the next uri based on base uri and location header fragment
/// See <https://tools.ietf.org/html/rfc3986#section-4.2>
@ -96,7 +97,7 @@ pub async fn fetch_once(
client: Client,
url: &Url,
cached_etag: Option<String>,
) -> Result<FetchOnceResult, ErrBox> {
) -> Result<FetchOnceResult, AnyError> {
let url = url.clone();
let mut request = client.get(url.clone());
@ -140,7 +141,7 @@ pub async fn fetch_once(
let new_url = resolve_url_from_location(&url, location_string);
return Ok(FetchOnceResult::Redirect(new_url, headers_));
} else {
return Err(ErrBox::error(format!(
return Err(generic_error(format!(
"Redirection from '{}' did not provide location header",
url
)));
@ -150,7 +151,7 @@ pub async fn fetch_once(
if response.status().is_client_error() || response.status().is_server_error()
{
let err =
ErrBox::error(format!("Import '{}' failed: {}", &url, response.status()));
generic_error(format!("Import '{}' failed: {}", &url, response.status()));
return Err(err);
}

View file

@ -1,4 +1,4 @@
use deno_core::ErrBox;
use deno_core::error::AnyError;
use deno_core::ModuleSpecifier;
use indexmap::IndexMap;
use serde_json::Map;
@ -46,7 +46,7 @@ pub struct ImportMap {
}
impl ImportMap {
pub fn load(file_path: &str) -> Result<Self, ErrBox> {
pub fn load(file_path: &str) -> Result<Self, AnyError> {
let file_url = ModuleSpecifier::resolve_url_or_path(file_path)?.to_string();
let resolved_path = std::env::current_dir().unwrap().join(file_path);
debug!(
@ -67,7 +67,7 @@ impl ImportMap {
)
})?;
// The URL of the import map is the base URL for its values.
ImportMap::from_json(&file_url, &json_string).map_err(ErrBox::from)
ImportMap::from_json(&file_url, &json_string).map_err(AnyError::from)
}
pub fn from_json(

View file

@ -4,7 +4,7 @@ use crate::module_graph::{ModuleGraph, ModuleGraphFile, ModuleGraphLoader};
use crate::msg;
use crate::ModuleSpecifier;
use crate::Permissions;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@ -27,7 +27,7 @@ impl ModuleDepInfo {
pub async fn new(
global_state: &Arc<GlobalState>,
module_specifier: ModuleSpecifier,
) -> Result<ModuleDepInfo, ErrBox> {
) -> Result<ModuleDepInfo, AnyError> {
// First load module as if it was to be executed by worker
// including compilation step
let mut module_graph_loader = ModuleGraphLoader::new(

View file

@ -2,15 +2,15 @@
use crate::flags::Flags;
use crate::global_state::GlobalState;
use deno_core::ErrBox;
use deno_core::error::generic_error;
use deno_core::error::AnyError;
use deno_core::ModuleSpecifier;
use log::Level;
use regex::{Regex, RegexBuilder};
use std::env;
use std::fs;
use std::fs::File;
use std::io::Error;
use std::io::ErrorKind;
use std::io;
use std::io::Write;
#[cfg(not(windows))]
use std::os::unix::fs::PermissionsExt;
@ -32,14 +32,14 @@ pub fn is_remote_url(module_url: &str) -> bool {
lower.starts_with("http://") || lower.starts_with("https://")
}
fn validate_name(exec_name: &str) -> Result<(), Error> {
fn validate_name(exec_name: &str) -> Result<(), AnyError> {
if EXEC_NAME_RE.is_match(exec_name) {
Ok(())
} else {
Err(Error::new(
ErrorKind::Other,
format!("Invalid executable name: {}", exec_name),
))
Err(generic_error(format!(
"Invalid executable name: {}",
exec_name
)))
}
}
@ -50,7 +50,7 @@ fn validate_name(exec_name: &str) -> Result<(), Error> {
fn generate_executable_file(
file_path: PathBuf,
args: Vec<String>,
) -> Result<(), Error> {
) -> Result<(), AnyError> {
let args: Vec<String> = args.iter().map(|c| format!("\"{}\"", c)).collect();
let template = format!(
"% generated by deno install %\n@deno.exe {} %*\n",
@ -65,7 +65,7 @@ fn generate_executable_file(
fn generate_executable_file(
file_path: PathBuf,
args: Vec<String>,
) -> Result<(), Error> {
) -> Result<(), AnyError> {
let args: Vec<String> = args.iter().map(|c| format!("\"{}\"", c)).collect();
let template = format!(
r#"#!/bin/sh
@ -87,7 +87,7 @@ async fn generate_bundle(
flags: Flags,
module_specifier: ModuleSpecifier,
script_path: PathBuf,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let global_state = GlobalState::new(flags.clone())?;
let source = global_state
.ts_compiler
@ -98,7 +98,7 @@ async fn generate_bundle(
Ok(())
}
fn get_installer_root() -> Result<PathBuf, Error> {
fn get_installer_root() -> Result<PathBuf, io::Error> {
if let Ok(env_dir) = env::var("DENO_INSTALL_ROOT") {
if !env_dir.is_empty() {
return PathBuf::from(env_dir).canonicalize();
@ -111,8 +111,8 @@ fn get_installer_root() -> Result<PathBuf, Error> {
env::var_os(home_env_var)
.map(PathBuf::from)
.ok_or_else(|| {
Error::new(
ErrorKind::NotFound,
io::Error::new(
io::ErrorKind::NotFound,
format!("${} is not defined", home_env_var),
)
})?;
@ -142,7 +142,7 @@ pub async fn install(
name: Option<String>,
root: Option<PathBuf>,
force: bool,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let root = if let Some(root) = root {
root.canonicalize()?
} else {
@ -153,10 +153,7 @@ pub async fn install(
// ensure directory exists
if let Ok(metadata) = fs::metadata(&installation_dir) {
if !metadata.is_dir() {
return Err(ErrBox::from(Error::new(
ErrorKind::Other,
"Installation path is not a directory",
)));
return Err(generic_error("Installation path is not a directory"));
}
} else {
fs::create_dir_all(&installation_dir)?;
@ -170,10 +167,9 @@ pub async fn install(
let name = match name {
Some(name) => name,
None => return Err(ErrBox::from(Error::new(
ErrorKind::Other,
None => return Err(generic_error(
"An executable name was not provided. One could not be inferred from the URL. Aborting.",
))),
)),
};
validate_name(name.as_str())?;
@ -185,10 +181,9 @@ pub async fn install(
}
if file_path.exists() && !force {
return Err(ErrBox::from(Error::new(
ErrorKind::Other,
return Err(generic_error(
"Existing installation found. Aborting (Use -f to overwrite).",
)));
));
};
let mut executable_args = vec!["run".to_string()];
@ -206,10 +201,7 @@ pub async fn install(
Level::Debug => "debug",
Level::Info => "info",
_ => {
return Err(ErrBox::from(Error::new(
ErrorKind::Other,
format!("invalid log level {}", log_level),
)))
return Err(generic_error(format!("invalid log level {}", log_level)))
}
};
executable_args.push(log_level.to_string());

View file

@ -12,7 +12,8 @@ use crate::fmt::collect_files;
use crate::fmt::run_parallelized;
use crate::fmt_errors;
use crate::msg;
use deno_core::ErrBox;
use deno_core::error::generic_error;
use deno_core::error::AnyError;
use deno_lint::diagnostic::LintDiagnostic;
use deno_lint::linter::Linter;
use deno_lint::linter::LinterBuilder;
@ -42,7 +43,7 @@ pub async fn lint_files(
args: Vec<String>,
ignore: Vec<String>,
json: bool,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
if args.len() == 1 && args[0] == "-" {
return lint_stdin(json);
}
@ -127,7 +128,7 @@ fn create_linter(syntax: Syntax, rules: Vec<Box<dyn LintRule>>) -> Linter {
fn lint_file(
file_path: PathBuf,
) -> Result<(Vec<LintDiagnostic>, String), ErrBox> {
) -> Result<(Vec<LintDiagnostic>, String), AnyError> {
let file_name = file_path.to_string_lossy().to_string();
let source_code = fs::read_to_string(&file_path)?;
let media_type = msg::MediaType::from(&file_path);
@ -144,10 +145,10 @@ fn lint_file(
/// Lint stdin and write result to stdout.
/// Treats input as TypeScript.
/// Compatible with `--json` flag.
fn lint_stdin(json: bool) -> Result<(), ErrBox> {
fn lint_stdin(json: bool) -> Result<(), AnyError> {
let mut source = String::new();
if stdin().read_to_string(&mut source).is_err() {
return Err(ErrBox::error("Failed to read from stdin"));
return Err(generic_error("Failed to read from stdin"));
}
let reporter_kind = if json {
@ -188,7 +189,7 @@ fn lint_stdin(json: bool) -> Result<(), ErrBox> {
trait LintReporter {
fn visit_diagnostic(&mut self, d: &LintDiagnostic, source_lines: Vec<&str>);
fn visit_error(&mut self, file_path: &str, err: &ErrBox);
fn visit_error(&mut self, file_path: &str, err: &AnyError);
fn close(&mut self, check_count: usize);
}
@ -229,7 +230,7 @@ impl LintReporter for PrettyLintReporter {
eprintln!("{}\n", message);
}
fn visit_error(&mut self, file_path: &str, err: &ErrBox) {
fn visit_error(&mut self, file_path: &str, err: &AnyError) {
eprintln!("Error linting: {}", file_path);
eprintln!(" {}", err);
}
@ -309,7 +310,7 @@ impl LintReporter for JsonLintReporter {
self.diagnostics.push(d.clone());
}
fn visit_error(&mut self, file_path: &str, err: &ErrBox) {
fn visit_error(&mut self, file_path: &str, err: &AnyError) {
self.errors.push(LintError {
file_path: file_path.to_string(),
message: err.to_string(),

View file

@ -80,8 +80,8 @@ use crate::global_state::GlobalState;
use crate::msg::MediaType;
use crate::permissions::Permissions;
use crate::worker::MainWorker;
use deno_core::error::AnyError;
use deno_core::v8_set_flags;
use deno_core::ErrBox;
use deno_core::ModuleSpecifier;
use deno_doc as doc;
use deno_doc::parser::DocFileLoader;
@ -113,18 +113,18 @@ fn write_to_stdout_ignore_sigpipe(bytes: &[u8]) -> Result<(), std::io::Error> {
}
}
fn write_json_to_stdout<T>(value: &T) -> Result<(), ErrBox>
fn write_json_to_stdout<T>(value: &T) -> Result<(), AnyError>
where
T: ?Sized + serde::ser::Serialize,
{
let writer = std::io::BufWriter::new(std::io::stdout());
serde_json::to_writer_pretty(writer, value).map_err(ErrBox::from)
serde_json::to_writer_pretty(writer, value).map_err(AnyError::from)
}
fn print_cache_info(
state: &Arc<GlobalState>,
json: bool,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let deno_dir = &state.dir.root;
let modules_cache = &state.file_fetcher.http_cache.location;
let typescript_cache = &state.dir.gen_cache.location;
@ -171,7 +171,7 @@ async fn info_command(
flags: Flags,
file: Option<String>,
json: bool,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
if json && !flags.unstable {
exit_unstable("--json");
}
@ -200,7 +200,7 @@ async fn install_command(
name: Option<String>,
root: Option<PathBuf>,
force: bool,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
installer::install(flags, &module_url, args, name, root, force).await
}
@ -210,7 +210,7 @@ async fn lint_command(
list_rules: bool,
ignore: Vec<String>,
json: bool,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
if !flags.unstable {
exit_unstable("lint");
}
@ -223,7 +223,10 @@ async fn lint_command(
lint::lint_files(files, ignore, json).await
}
async fn cache_command(flags: Flags, files: Vec<String>) -> Result<(), ErrBox> {
async fn cache_command(
flags: Flags,
files: Vec<String>,
) -> Result<(), AnyError> {
let main_module =
ModuleSpecifier::resolve_url_or_path("./$deno$cache.ts").unwrap();
let global_state = GlobalState::new(flags)?;
@ -244,7 +247,7 @@ async fn eval_command(
code: String,
as_typescript: bool,
print: bool,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
// Force TypeScript compile.
let main_module =
ModuleSpecifier::resolve_url_or_path("./$deno$eval.ts").unwrap();
@ -287,7 +290,7 @@ async fn bundle_command(
flags: Flags,
source_file: String,
out_file: Option<PathBuf>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let module_specifier = ModuleSpecifier::resolve_url_or_path(&source_file)?;
debug!(">>>>> bundle START");
@ -328,7 +331,7 @@ async fn doc_command(
json: bool,
maybe_filter: Option<String>,
private: bool,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let global_state = GlobalState::new(flags.clone())?;
let source_file = source_file.unwrap_or_else(|| "--builtin".to_string());
@ -422,11 +425,11 @@ async fn doc_command(
)
};
write_to_stdout_ignore_sigpipe(details.as_bytes()).map_err(ErrBox::from)
write_to_stdout_ignore_sigpipe(details.as_bytes()).map_err(AnyError::from)
}
}
async fn run_repl(flags: Flags) -> Result<(), ErrBox> {
async fn run_repl(flags: Flags) -> Result<(), AnyError> {
let main_module =
ModuleSpecifier::resolve_url_or_path("./$deno$repl.ts").unwrap();
let global_state = GlobalState::new(flags)?;
@ -436,7 +439,7 @@ async fn run_repl(flags: Flags) -> Result<(), ErrBox> {
}
}
async fn run_from_stdin(flags: Flags) -> Result<(), ErrBox> {
async fn run_from_stdin(flags: Flags) -> Result<(), AnyError> {
let global_state = GlobalState::new(flags.clone())?;
let main_module =
ModuleSpecifier::resolve_url_or_path("./$deno$stdin.ts").unwrap();
@ -468,7 +471,7 @@ async fn run_from_stdin(flags: Flags) -> Result<(), ErrBox> {
Ok(())
}
async fn run_with_watch(flags: Flags, script: String) -> Result<(), ErrBox> {
async fn run_with_watch(flags: Flags, script: String) -> Result<(), AnyError> {
let main_module = ModuleSpecifier::resolve_url_or_path(&script)?;
let global_state = GlobalState::new(flags.clone())?;
@ -510,7 +513,7 @@ async fn run_with_watch(flags: Flags, script: String) -> Result<(), ErrBox> {
.await
}
async fn run_command(flags: Flags, script: String) -> Result<(), ErrBox> {
async fn run_command(flags: Flags, script: String) -> Result<(), AnyError> {
// Read script content from stdin
if script == "-" {
return run_from_stdin(flags).await;
@ -539,7 +542,7 @@ async fn test_command(
allow_none: bool,
filter: Option<String>,
coverage: bool,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let global_state = GlobalState::new(flags.clone())?;
let cwd = std::env::current_dir().expect("No current directory");
let include = include.unwrap_or_else(|| vec![".".to_string()]);

View file

@ -13,7 +13,9 @@ use crate::tsc::TsReferenceDesc;
use crate::tsc::TsReferenceKind;
use crate::tsc::AVAILABLE_LIBS;
use crate::version;
use deno_core::ErrBox;
use deno_core::error::custom_error;
use deno_core::error::generic_error;
use deno_core::error::AnyError;
use deno_core::ModuleSpecifier;
use futures::stream::FuturesUnordered;
use futures::stream::StreamExt;
@ -28,14 +30,17 @@ use std::pin::Pin;
// TODO(bartlomieju): it'd be great if this function returned
// more structured data and possibly format the same as TS diagnostics.
/// Decorate error with location of import that caused the error.
fn err_with_location(e: ErrBox, maybe_location: Option<&Location>) -> ErrBox {
fn err_with_location(
e: AnyError,
maybe_location: Option<&Location>,
) -> AnyError {
if let Some(location) = maybe_location {
let location_str = format!(
"\nImported from \"{}:{}\"",
location.filename, location.line
);
let err_str = e.to_string();
ErrBox::error(format!("{}{}", err_str, location_str))
generic_error(format!("{}{}", err_str, location_str))
} else {
e
}
@ -46,11 +51,11 @@ fn validate_no_downgrade(
module_specifier: &ModuleSpecifier,
maybe_referrer: Option<&ModuleSpecifier>,
maybe_location: Option<&Location>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
if let Some(referrer) = maybe_referrer.as_ref() {
if let "https" = referrer.as_url().scheme() {
if let "http" = module_specifier.as_url().scheme() {
let e = ErrBox::new("PermissionDenied",
let e = custom_error("PermissionDenied",
"Modules loaded over https:// are not allowed to import modules over http://"
);
return Err(err_with_location(e, maybe_location));
@ -66,7 +71,7 @@ fn validate_no_file_from_remote(
module_specifier: &ModuleSpecifier,
maybe_referrer: Option<&ModuleSpecifier>,
maybe_location: Option<&Location>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
if let Some(referrer) = maybe_referrer.as_ref() {
let referrer_url = referrer.as_url();
match referrer_url.scheme() {
@ -75,7 +80,7 @@ fn validate_no_file_from_remote(
match specifier_url.scheme() {
"http" | "https" => {}
_ => {
let e = ErrBox::new(
let e = custom_error(
"PermissionDenied",
"Remote modules are not allowed to statically import local \
modules. Use dynamic import instead.",
@ -98,7 +103,7 @@ fn resolve_imports_and_references(
maybe_import_map: Option<&ImportMap>,
import_descs: Vec<ImportDesc>,
ref_descs: Vec<TsReferenceDesc>,
) -> Result<(Vec<ImportDescriptor>, Vec<ReferenceDescriptor>), ErrBox> {
) -> Result<(Vec<ImportDescriptor>, Vec<ReferenceDescriptor>), AnyError> {
let mut imports = vec![];
let mut references = vec![];
@ -245,8 +250,9 @@ impl ModuleGraphFile {
}
}
type SourceFileFuture =
Pin<Box<dyn Future<Output = Result<(ModuleSpecifier, SourceFile), ErrBox>>>>;
type SourceFileFuture = Pin<
Box<dyn Future<Output = Result<(ModuleSpecifier, SourceFile), AnyError>>>,
>;
pub struct ModuleGraphLoader {
permissions: Permissions,
@ -289,7 +295,7 @@ impl ModuleGraphLoader {
&mut self,
specifier: &ModuleSpecifier,
maybe_referrer: Option<ModuleSpecifier>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
self.download_module(specifier.clone(), maybe_referrer, None)?;
loop {
@ -311,7 +317,7 @@ impl ModuleGraphLoader {
&mut self,
_root_name: &str,
source_map: &HashMap<String, String>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
for (spec, source_code) in source_map.iter() {
self.visit_memory_module(spec.to_string(), source_code.to_string())?;
}
@ -328,7 +334,7 @@ impl ModuleGraphLoader {
&mut self,
specifier: String,
source_code: String,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let mut referenced_files = vec![];
let mut lib_directives = vec![];
let mut types_directives = vec![];
@ -398,7 +404,7 @@ impl ModuleGraphLoader {
module_specifier: ModuleSpecifier,
maybe_referrer: Option<ModuleSpecifier>,
maybe_location: Option<Location>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
if self.has_downloaded.contains(&module_specifier) {
return Ok(());
}
@ -441,7 +447,7 @@ impl ModuleGraphLoader {
&mut self,
module_specifier: &ModuleSpecifier,
source_file: SourceFile,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let mut imports = vec![];
let mut referenced_files = vec![];
let mut lib_directives = vec![];
@ -592,7 +598,7 @@ mod tests {
async fn build_graph(
module_specifier: &ModuleSpecifier,
) -> Result<ModuleGraph, ErrBox> {
) -> Result<ModuleGraph, AnyError> {
let global_state = GlobalState::new(Default::default()).unwrap();
let mut graph_loader = ModuleGraphLoader::new(
global_state.file_fetcher.clone(),

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::Op;
use deno_core::OpFn;
use deno_core::OpState;
@ -15,8 +15,8 @@ use std::rc::Rc;
use std::slice;
pub enum MinimalOp {
Sync(Result<i32, ErrBox>),
Async(Pin<Box<dyn Future<Output = Result<i32, ErrBox>>>>),
Sync(Result<i32, AnyError>),
Async(Pin<Box<dyn Future<Output = Result<i32, AnyError>>>>),
}
#[derive(Copy, Clone, Debug, PartialEq)]
@ -144,14 +144,14 @@ where
let mut record = match parse_min_record(&record_buf) {
Some(r) => r,
None => {
let error = ErrBox::type_error("Unparsable control buffer");
let error_class = (state.borrow().get_error_class_fn)(&error);
let error_class = b"TypeError";
let error_message = b"Unparsable control buffer";
let error_record = ErrorRecord {
promise_id: 0,
arg: -1,
error_len: error_class.len() as i32,
error_class: error_class.as_bytes(),
error_message: error.to_string().as_bytes().to_owned(),
error_class,
error_message: error_message[..].to_owned(),
};
return Op::Sync(error_record.into());
}

View file

@ -3,7 +3,7 @@
use crate::diagnostics::Diagnostics;
use crate::source_maps::get_orig_position;
use crate::source_maps::CachedMaps;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use serde_derive::Deserialize;
@ -27,7 +27,7 @@ fn op_apply_source_map(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ApplySourceMap = serde_json::from_value(args)?;
let mut mappings_map: CachedMaps = HashMap::new();
@ -51,7 +51,7 @@ fn op_format_diagnostic(
_state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let diagnostic: Diagnostics = serde_json::from_value(args)?;
Ok(json!(diagnostic.to_string()))
}

View file

@ -1,9 +1,13 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use super::io::{StreamResource, StreamResourceHolder};
use crate::http_util::{create_http_client, HttpBody};
use super::io::StreamResource;
use super::io::StreamResourceHolder;
use crate::http_util::create_http_client;
use crate::http_util::HttpBody;
use deno_core::error::bad_resource_id;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use http::header::HeaderName;
@ -35,7 +39,7 @@ async fn op_fetch(
state: Rc<RefCell<OpState>>,
args: Value,
data: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: FetchArgs = serde_json::from_value(args)?;
let url = args.url;
@ -44,7 +48,7 @@ async fn op_fetch(
let r = state
.resource_table
.get::<HttpClientResource>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
r.client.clone()
} else {
let cli_state = super::cli_state2(&state);
@ -62,10 +66,7 @@ async fn op_fetch(
// Check scheme before asking for net permission
let scheme = url_.scheme();
if scheme != "http" && scheme != "https" {
return Err(ErrBox::type_error(format!(
"scheme '{}' not supported",
scheme
)));
return Err(type_error(format!("scheme '{}' not supported", scheme)));
}
super::cli_state2(&state).check_net_url(&url_)?;
@ -133,7 +134,7 @@ fn op_create_http_client(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: CreateHttpClientOptions = serde_json::from_value(args)?;
if let Some(ca_file) = args.ca_file.clone() {

View file

@ -2,8 +2,10 @@
// Some deserializer fields are only used on Unix and Windows build fails without it
use super::io::std_file_resource;
use super::io::{FileMetadata, StreamResource, StreamResourceHolder};
use deno_core::error::custom_error;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use rand::thread_rng;
@ -20,6 +22,11 @@ use std::rc::Rc;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
#[cfg(not(unix))]
use deno_core::error::generic_error;
#[cfg(not(unix))]
use deno_core::error::not_supported;
pub fn init(rt: &mut deno_core::JsRuntime) {
super::reg_json_sync(rt, "op_open_sync", op_open_sync);
super::reg_json_async(rt, "op_open_async", op_open_async);
@ -96,10 +103,10 @@ pub fn init(rt: &mut deno_core::JsRuntime) {
super::reg_json_async(rt, "op_utime_async", op_utime_async);
}
fn into_string(s: std::ffi::OsString) -> Result<String, ErrBox> {
fn into_string(s: std::ffi::OsString) -> Result<String, AnyError> {
s.into_string().map_err(|s| {
let message = format!("File name or path {:?} is not valid UTF-8", s);
ErrBox::new("InvalidData", message)
custom_error("InvalidData", message)
})
}
@ -126,7 +133,7 @@ struct OpenOptions {
fn open_helper(
state: &mut OpState,
args: Value,
) -> Result<(PathBuf, std::fs::OpenOptions), ErrBox> {
) -> Result<(PathBuf, std::fs::OpenOptions), AnyError> {
let args: OpenArgs = serde_json::from_value(args)?;
let path = Path::new(&args.path).to_path_buf();
@ -170,7 +177,7 @@ fn op_open_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let (path, open_options) = open_helper(state, args)?;
let std_file = open_options.open(path)?;
let tokio_file = tokio::fs::File::from_std(std_file);
@ -188,7 +195,7 @@ async fn op_open_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let (path, open_options) = open_helper(&mut state.borrow_mut(), args)?;
let tokio_file = tokio::fs::OpenOptions::from(open_options)
.open(path)
@ -211,7 +218,7 @@ struct SeekArgs {
whence: i32,
}
fn seek_helper(args: Value) -> Result<(u32, SeekFrom), ErrBox> {
fn seek_helper(args: Value) -> Result<(u32, SeekFrom), AnyError> {
let args: SeekArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
let offset = args.offset;
@ -222,7 +229,7 @@ fn seek_helper(args: Value) -> Result<(u32, SeekFrom), ErrBox> {
1 => SeekFrom::Current(offset),
2 => SeekFrom::End(offset),
_ => {
return Err(ErrBox::type_error(format!("Invalid seek mode: {}", whence)));
return Err(type_error(format!("Invalid seek mode: {}", whence)));
}
};
@ -233,11 +240,11 @@ fn op_seek_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let (rid, seek_from) = seek_helper(args)?;
let pos = std_file_resource(state, rid, |r| match r {
Ok(std_file) => std_file.seek(seek_from).map_err(ErrBox::from),
Err(_) => Err(ErrBox::type_error(
Ok(std_file) => std_file.seek(seek_from).map_err(AnyError::from),
Err(_) => Err(type_error(
"cannot seek on this type of resource".to_string(),
)),
})?;
@ -248,13 +255,13 @@ async fn op_seek_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let (rid, seek_from) = seek_helper(args)?;
// TODO(ry) This is a fake async op. We need to use poll_fn,
// tokio::fs::File::start_seek and tokio::fs::File::poll_complete
let pos = std_file_resource(&mut state.borrow_mut(), rid, |r| match r {
Ok(std_file) => std_file.seek(seek_from).map_err(ErrBox::from),
Err(_) => Err(ErrBox::type_error(
Ok(std_file) => std_file.seek(seek_from).map_err(AnyError::from),
Err(_) => Err(type_error(
"cannot seek on this type of resource".to_string(),
)),
})?;
@ -271,7 +278,7 @@ fn op_fdatasync_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
{
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.fdatasync");
@ -279,10 +286,8 @@ fn op_fdatasync_sync(
let args: FdatasyncArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
std_file_resource(state, rid, |r| match r {
Ok(std_file) => std_file.sync_data().map_err(ErrBox::from),
Err(_) => Err(ErrBox::type_error(
"cannot sync this type of resource".to_string(),
)),
Ok(std_file) => std_file.sync_data().map_err(AnyError::from),
Err(_) => Err(type_error("cannot sync this type of resource".to_string())),
})?;
Ok(json!({}))
}
@ -291,16 +296,14 @@ async fn op_fdatasync_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
super::cli_state2(&state).check_unstable("Deno.fdatasync");
let args: FdatasyncArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
std_file_resource(&mut state.borrow_mut(), rid, |r| match r {
Ok(std_file) => std_file.sync_data().map_err(ErrBox::from),
Err(_) => Err(ErrBox::type_error(
"cannot sync this type of resource".to_string(),
)),
Ok(std_file) => std_file.sync_data().map_err(AnyError::from),
Err(_) => Err(type_error("cannot sync this type of resource".to_string())),
})?;
Ok(json!({}))
}
@ -315,7 +318,7 @@ fn op_fsync_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
{
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.fsync");
@ -323,10 +326,8 @@ fn op_fsync_sync(
let args: FsyncArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
std_file_resource(state, rid, |r| match r {
Ok(std_file) => std_file.sync_all().map_err(ErrBox::from),
Err(_) => Err(ErrBox::type_error(
"cannot sync this type of resource".to_string(),
)),
Ok(std_file) => std_file.sync_all().map_err(AnyError::from),
Err(_) => Err(type_error("cannot sync this type of resource".to_string())),
})?;
Ok(json!({}))
}
@ -335,16 +336,14 @@ async fn op_fsync_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
super::cli_state2(&state).check_unstable("Deno.fsync");
let args: FsyncArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
std_file_resource(&mut state.borrow_mut(), rid, |r| match r {
Ok(std_file) => std_file.sync_all().map_err(ErrBox::from),
Err(_) => Err(ErrBox::type_error(
"cannot sync this type of resource".to_string(),
)),
Ok(std_file) => std_file.sync_all().map_err(AnyError::from),
Err(_) => Err(type_error("cannot sync this type of resource".to_string())),
})?;
Ok(json!({}))
}
@ -359,7 +358,7 @@ fn op_fstat_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
{
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.fstat");
@ -367,10 +366,8 @@ fn op_fstat_sync(
let args: FstatArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
let metadata = std_file_resource(state, rid, |r| match r {
Ok(std_file) => std_file.metadata().map_err(ErrBox::from),
Err(_) => Err(ErrBox::type_error(
"cannot stat this type of resource".to_string(),
)),
Ok(std_file) => std_file.metadata().map_err(AnyError::from),
Err(_) => Err(type_error("cannot stat this type of resource".to_string())),
})?;
Ok(get_stat_json(metadata).unwrap())
}
@ -379,17 +376,17 @@ async fn op_fstat_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
super::cli_state2(&state).check_unstable("Deno.fstat");
let args: FstatArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
let metadata =
std_file_resource(&mut state.borrow_mut(), rid, |r| match r {
Ok(std_file) => std_file.metadata().map_err(ErrBox::from),
Err(_) => Err(ErrBox::type_error(
"cannot stat this type of resource".to_string(),
)),
Ok(std_file) => std_file.metadata().map_err(AnyError::from),
Err(_) => {
Err(type_error("cannot stat this type of resource".to_string()))
}
})?;
Ok(get_stat_json(metadata).unwrap())
}
@ -403,7 +400,7 @@ fn op_umask(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
{
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.umask");
@ -415,7 +412,7 @@ fn op_umask(
#[cfg(not(unix))]
{
let _ = args.mask; // avoid unused warning.
Err(ErrBox::not_supported())
Err(not_supported())
}
#[cfg(unix)]
{
@ -444,7 +441,7 @@ fn op_chdir(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ChdirArgs = serde_json::from_value(args)?;
let d = PathBuf::from(&args.directory);
let cli_state = super::cli_state(state);
@ -465,7 +462,7 @@ fn op_mkdir_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: MkdirArgs = serde_json::from_value(args)?;
let path = Path::new(&args.path).to_path_buf();
let mode = args.mode.unwrap_or(0o777) & 0o777;
@ -487,7 +484,7 @@ async fn op_mkdir_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: MkdirArgs = serde_json::from_value(args)?;
let path = Path::new(&args.path).to_path_buf();
let mode = args.mode.unwrap_or(0o777) & 0o777;
@ -521,7 +518,7 @@ fn op_chmod_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ChmodArgs = serde_json::from_value(args)?;
let path = Path::new(&args.path).to_path_buf();
let mode = args.mode & 0o777;
@ -541,7 +538,7 @@ fn op_chmod_sync(
{
// Still check file/dir exists on Windows
let _metadata = std::fs::metadata(&path)?;
Err(ErrBox::error("Not implemented"))
Err(generic_error("Not implemented"))
}
}
@ -549,7 +546,7 @@ async fn op_chmod_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ChmodArgs = serde_json::from_value(args)?;
let path = Path::new(&args.path).to_path_buf();
let mode = args.mode & 0o777;
@ -570,7 +567,7 @@ async fn op_chmod_async(
{
// Still check file/dir exists on Windows
let _metadata = std::fs::metadata(&path)?;
Err(ErrBox::not_supported())
Err(not_supported())
}
})
.await
@ -589,7 +586,7 @@ fn op_chown_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ChownArgs = serde_json::from_value(args)?;
let path = Path::new(&args.path).to_path_buf();
let cli_state = super::cli_state(state);
@ -611,7 +608,7 @@ fn op_chown_sync(
// TODO Implement chown for Windows
#[cfg(not(unix))]
{
Err(ErrBox::error("Not implemented"))
Err(generic_error("Not implemented"))
}
}
@ -619,7 +616,7 @@ async fn op_chown_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ChownArgs = serde_json::from_value(args)?;
let path = Path::new(&args.path).to_path_buf();
@ -642,7 +639,7 @@ async fn op_chown_async(
}
// TODO Implement chown for Windows
#[cfg(not(unix))]
Err(ErrBox::not_supported())
Err(not_supported())
})
.await
.unwrap()
@ -659,7 +656,7 @@ fn op_remove_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: RemoveArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
let recursive = args.recursive;
@ -703,7 +700,7 @@ async fn op_remove_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: RemoveArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
let recursive = args.recursive;
@ -757,7 +754,7 @@ fn op_copy_file_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: CopyFileArgs = serde_json::from_value(args)?;
let from = PathBuf::from(&args.from);
let to = PathBuf::from(&args.to);
@ -771,7 +768,7 @@ fn op_copy_file_sync(
// See https://github.com/rust-lang/rust/issues/54800
// Once the issue is resolved, we should remove this workaround.
if cfg!(unix) && !from.is_file() {
return Err(ErrBox::new("NotFound", "File not found"));
return Err(custom_error("NotFound", "File not found"));
}
// returns size of from as u64 (we ignore)
@ -783,7 +780,7 @@ async fn op_copy_file_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: CopyFileArgs = serde_json::from_value(args)?;
let from = PathBuf::from(&args.from);
let to = PathBuf::from(&args.to);
@ -798,7 +795,7 @@ async fn op_copy_file_async(
// See https://github.com/rust-lang/rust/issues/54800
// Once the issue is resolved, we should remove this workaround.
if cfg!(unix) && !from.is_file() {
return Err(ErrBox::new("NotFound", "File not found"));
return Err(custom_error("NotFound", "File not found"));
}
// returns size of from as u64 (we ignore)
@ -825,7 +822,7 @@ fn to_msec(maybe_time: Result<SystemTime, io::Error>) -> Value {
}
#[inline(always)]
fn get_stat_json(metadata: std::fs::Metadata) -> Result<Value, ErrBox> {
fn get_stat_json(metadata: std::fs::Metadata) -> Result<Value, AnyError> {
// Unix stat member (number types only). 0 if not on unix.
macro_rules! usm {
($member:ident) => {{
@ -878,7 +875,7 @@ fn op_stat_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: StatArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
let lstat = args.lstat;
@ -897,7 +894,7 @@ async fn op_stat_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: StatArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
let lstat = args.lstat;
@ -927,7 +924,7 @@ fn op_realpath_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: RealpathArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
@ -953,7 +950,7 @@ async fn op_realpath_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: RealpathArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
@ -989,7 +986,7 @@ fn op_read_dir_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ReadDirArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
@ -1022,7 +1019,7 @@ async fn op_read_dir_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ReadDirArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
super::cli_state2(&state).check_read(&path)?;
@ -1063,7 +1060,7 @@ fn op_rename_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: RenameArgs = serde_json::from_value(args)?;
let oldpath = PathBuf::from(&args.oldpath);
let newpath = PathBuf::from(&args.newpath);
@ -1081,7 +1078,7 @@ async fn op_rename_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: RenameArgs = serde_json::from_value(args)?;
let oldpath = PathBuf::from(&args.oldpath);
let newpath = PathBuf::from(&args.newpath);
@ -1115,7 +1112,7 @@ fn op_link_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.link");
let args: LinkArgs = serde_json::from_value(args)?;
@ -1134,7 +1131,7 @@ async fn op_link_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state2(&state);
cli_state.check_unstable("Deno.link");
@ -1174,7 +1171,7 @@ fn op_symlink_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.symlink");
let args: SymlinkArgs = serde_json::from_value(args)?;
@ -1202,7 +1199,7 @@ fn op_symlink_sync(
Some(options) => match options._type.as_ref() {
"file" => symlink_file(&oldpath, &newpath)?,
"dir" => symlink_dir(&oldpath, &newpath)?,
_ => return Err(ErrBox::type_error("unsupported type")),
_ => return Err(type_error("unsupported type")),
},
None => {
let old_meta = std::fs::metadata(&oldpath);
@ -1214,7 +1211,7 @@ fn op_symlink_sync(
symlink_dir(&oldpath, &newpath)?
}
}
Err(_) => return Err(ErrBox::type_error("you must pass a `options` argument for non-existent target path in windows".to_string())),
Err(_) => return Err(type_error("you must pass a `options` argument for non-existent target path in windows".to_string())),
}
}
};
@ -1226,7 +1223,7 @@ async fn op_symlink_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state2(&state);
cli_state.check_unstable("Deno.symlink");
@ -1252,7 +1249,7 @@ async fn op_symlink_async(
Some(options) => match options._type.as_ref() {
"file" => symlink_file(&oldpath, &newpath)?,
"dir" => symlink_dir(&oldpath, &newpath)?,
_ => return Err(ErrBox::type_error("unsupported type")),
_ => return Err(type_error("unsupported type")),
},
None => {
let old_meta = std::fs::metadata(&oldpath);
@ -1264,7 +1261,7 @@ async fn op_symlink_async(
symlink_dir(&oldpath, &newpath)?
}
}
Err(_) => return Err(ErrBox::type_error("you must pass a `options` argument for non-existent target path in windows".to_string())),
Err(_) => return Err(type_error("you must pass a `options` argument for non-existent target path in windows".to_string())),
}
}
};
@ -1285,7 +1282,7 @@ fn op_read_link_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ReadLinkArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
@ -1302,7 +1299,7 @@ async fn op_read_link_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ReadLinkArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
super::cli_state2(&state).check_read(&path)?;
@ -1327,7 +1324,7 @@ fn op_ftruncate_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
{
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.ftruncate");
@ -1336,8 +1333,8 @@ fn op_ftruncate_sync(
let rid = args.rid as u32;
let len = args.len as u64;
std_file_resource(state, rid, |r| match r {
Ok(std_file) => std_file.set_len(len).map_err(ErrBox::from),
Err(_) => Err(ErrBox::type_error("cannot truncate this type of resource")),
Ok(std_file) => std_file.set_len(len).map_err(AnyError::from),
Err(_) => Err(type_error("cannot truncate this type of resource")),
})?;
Ok(json!({}))
}
@ -1346,14 +1343,14 @@ async fn op_ftruncate_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
super::cli_state2(&state).check_unstable("Deno.ftruncate");
let args: FtruncateArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
let len = args.len as u64;
std_file_resource(&mut state.borrow_mut(), rid, |r| match r {
Ok(std_file) => std_file.set_len(len).map_err(ErrBox::from),
Err(_) => Err(ErrBox::type_error("cannot truncate this type of resource")),
Ok(std_file) => std_file.set_len(len).map_err(AnyError::from),
Err(_) => Err(type_error("cannot truncate this type of resource")),
})?;
Ok(json!({}))
}
@ -1369,7 +1366,7 @@ fn op_truncate_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: TruncateArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
let len = args.len;
@ -1387,7 +1384,7 @@ async fn op_truncate_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: TruncateArgs = serde_json::from_value(args)?;
let path = PathBuf::from(&args.path);
let len = args.len;
@ -1459,7 +1456,7 @@ fn op_make_temp_dir_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: MakeTempArgs = serde_json::from_value(args)?;
let dir = args.dir.map(|s| PathBuf::from(&s));
@ -1488,7 +1485,7 @@ async fn op_make_temp_dir_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: MakeTempArgs = serde_json::from_value(args)?;
let dir = args.dir.map(|s| PathBuf::from(&s));
@ -1521,7 +1518,7 @@ fn op_make_temp_file_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: MakeTempArgs = serde_json::from_value(args)?;
let dir = args.dir.map(|s| PathBuf::from(&s));
@ -1550,7 +1547,7 @@ async fn op_make_temp_file_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: MakeTempArgs = serde_json::from_value(args)?;
let dir = args.dir.map(|s| PathBuf::from(&s));
@ -1592,7 +1589,7 @@ fn op_futime_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
{
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.futimeSync");
@ -1605,9 +1602,9 @@ fn op_futime_sync(
std_file_resource(state, rid, |r| match r {
Ok(std_file) => {
filetime::set_file_handle_times(std_file, Some(atime), Some(mtime))
.map_err(ErrBox::from)
.map_err(AnyError::from)
}
Err(_) => Err(ErrBox::type_error(
Err(_) => Err(type_error(
"cannot futime on this type of resource".to_string(),
)),
})?;
@ -1619,7 +1616,7 @@ async fn op_futime_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let mut state = state.borrow_mut();
let cli_state = super::cli_state(&state);
cli_state.check_unstable("Deno.futime");
@ -1631,9 +1628,9 @@ async fn op_futime_async(
std_file_resource(&mut state, rid, |r| match r {
Ok(std_file) => {
filetime::set_file_handle_times(std_file, Some(atime), Some(mtime))
.map_err(ErrBox::from)
.map_err(AnyError::from)
}
Err(_) => Err(ErrBox::type_error(
Err(_) => Err(type_error(
"cannot futime on this type of resource".to_string(),
)),
})?;
@ -1653,7 +1650,7 @@ fn op_utime_sync(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.utime");
@ -1671,7 +1668,7 @@ async fn op_utime_async(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let state = state.borrow();
let cli_state = super::cli_state(&state);
cli_state.check_unstable("Deno.utime");
@ -1695,7 +1692,7 @@ fn op_cwd(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let path = current_dir()?;
let cli_state = super::cli_state(state);
cli_state.check_read_blind(&path, "CWD")?;

View file

@ -1,7 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::error::bad_resource_id;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use futures::future::poll_fn;
@ -28,7 +29,7 @@ pub fn init(rt: &mut deno_core::JsRuntime) {
struct FsEventsResource {
#[allow(unused)]
watcher: RecommendedWatcher,
receiver: mpsc::Receiver<Result<FsEvent, ErrBox>>,
receiver: mpsc::Receiver<Result<FsEvent, AnyError>>,
}
/// Represents a file system event.
@ -67,18 +68,18 @@ fn op_fs_events_open(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
#[derive(Deserialize)]
struct OpenArgs {
recursive: bool,
paths: Vec<String>,
}
let args: OpenArgs = serde_json::from_value(args)?;
let (sender, receiver) = mpsc::channel::<Result<FsEvent, ErrBox>>(16);
let (sender, receiver) = mpsc::channel::<Result<FsEvent, AnyError>>(16);
let sender = std::sync::Mutex::new(sender);
let mut watcher: RecommendedWatcher =
Watcher::new_immediate(move |res: Result<NotifyEvent, NotifyError>| {
let res2 = res.map(FsEvent::from).map_err(ErrBox::from);
let res2 = res.map(FsEvent::from).map_err(AnyError::from);
let mut sender = sender.lock().unwrap();
// Ignore result, if send failed it means that watcher was already closed,
// but not all messages have been flushed.
@ -102,7 +103,7 @@ async fn op_fs_events_poll(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
#[derive(Deserialize)]
struct PollArgs {
rid: u32,
@ -113,7 +114,7 @@ async fn op_fs_events_poll(
let watcher = state
.resource_table
.get_mut::<FsEventsResource>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
watcher
.receiver
.poll_recv(cx)

View file

@ -2,7 +2,8 @@
//! https://url.spec.whatwg.org/#idna
use deno_core::ErrBox;
use deno_core::error::uri_error;
use deno_core::error::AnyError;
use deno_core::ZeroCopyBuf;
use idna::domain_to_ascii;
use idna::domain_to_ascii_strict;
@ -24,7 +25,7 @@ fn op_domain_to_ascii(
_state: &mut deno_core::OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: DomainToAscii = serde_json::from_value(args)?;
if args.be_strict {
domain_to_ascii_strict(args.domain.as_str())
@ -33,7 +34,7 @@ fn op_domain_to_ascii(
}
.map_err(|err| {
let message = format!("Invalid IDNA encoded domain name: {:?}", err);
ErrBox::new("URIError", message)
uri_error(message)
})
.map(|domain| json!(domain))
}

View file

@ -2,8 +2,11 @@ use super::dispatch_minimal::minimal_op;
use super::dispatch_minimal::MinimalOp;
use crate::http_util::HttpBody;
use crate::metrics::metrics_op;
use deno_core::error::bad_resource_id;
use deno_core::error::resource_unavailable;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::JsRuntime;
use deno_core::OpState;
use futures::future::poll_fn;
@ -117,8 +120,8 @@ fn get_stdio_stream(
}
}
fn no_buffer_specified() -> ErrBox {
ErrBox::type_error("no buffer specified")
fn no_buffer_specified() -> AnyError {
type_error("no buffer specified")
}
#[cfg(unix)]
@ -160,7 +163,7 @@ impl Drop for StreamResourceHolder {
}
impl StreamResourceHolder {
pub fn track_task(&mut self, cx: &Context) -> Result<usize, ErrBox> {
pub fn track_task(&mut self, cx: &Context) -> Result<usize, AnyError> {
let waker = futures::task::AtomicWaker::new();
waker.register(cx.waker());
// Its OK if it overflows
@ -201,13 +204,13 @@ impl<T: AsyncRead + Unpin> UnpinAsyncRead for T {}
impl<T: AsyncWrite + Unpin> UnpinAsyncWrite for T {}
/// `DenoAsyncRead` is the same as the `tokio_io::AsyncRead` trait
/// but uses an `ErrBox` error instead of `std::io:Error`
/// but uses an `AnyError` error instead of `std::io:Error`
pub trait DenoAsyncRead {
fn poll_read(
&mut self,
cx: &mut Context,
buf: &mut [u8],
) -> Poll<Result<usize, ErrBox>>;
) -> Poll<Result<usize, AnyError>>;
}
impl DenoAsyncRead for StreamResource {
@ -215,11 +218,11 @@ impl DenoAsyncRead for StreamResource {
&mut self,
cx: &mut Context,
buf: &mut [u8],
) -> Poll<Result<usize, ErrBox>> {
) -> Poll<Result<usize, AnyError>> {
use StreamResource::*;
let f: &mut dyn UnpinAsyncRead = match self {
FsFile(Some((f, _))) => f,
FsFile(None) => return Poll::Ready(Err(ErrBox::resource_unavailable())),
FsFile(None) => return Poll::Ready(Err(resource_unavailable())),
Stdin(f, _) => f,
TcpStream(Some(f)) => f,
#[cfg(not(windows))]
@ -229,7 +232,7 @@ impl DenoAsyncRead for StreamResource {
ChildStdout(f) => f,
ChildStderr(f) => f,
HttpBody(f) => f,
_ => return Err(ErrBox::bad_resource_id()).into(),
_ => return Err(bad_resource_id()).into(),
};
let v = ready!(Pin::new(f).poll_read(cx, buf))?;
Ok(v).into()
@ -258,11 +261,9 @@ pub fn op_read(
std_file
.read(&mut zero_copy[0])
.map(|n: usize| n as i32)
.map_err(ErrBox::from)
}
Err(_) => {
Err(ErrBox::type_error("sync read not allowed on this resource"))
.map_err(AnyError::from)
}
Err(_) => Err(type_error("sync read not allowed on this resource")),
})
})
} else {
@ -273,7 +274,7 @@ pub fn op_read(
let resource_holder = state
.resource_table
.get_mut::<StreamResourceHolder>(rid as u32)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
let mut task_tracker_id: Option<usize> = None;
let nread = match resource_holder.resource.poll_read(cx, &mut zero_copy)
@ -297,17 +298,17 @@ pub fn op_read(
}
/// `DenoAsyncWrite` is the same as the `tokio_io::AsyncWrite` trait
/// but uses an `ErrBox` error instead of `std::io:Error`
/// but uses an `AnyError` error instead of `std::io:Error`
pub trait DenoAsyncWrite {
fn poll_write(
&mut self,
cx: &mut Context,
buf: &[u8],
) -> Poll<Result<usize, ErrBox>>;
) -> Poll<Result<usize, AnyError>>;
fn poll_close(&mut self, cx: &mut Context) -> Poll<Result<(), ErrBox>>;
fn poll_close(&mut self, cx: &mut Context) -> Poll<Result<(), AnyError>>;
fn poll_flush(&mut self, cx: &mut Context) -> Poll<Result<(), ErrBox>>;
fn poll_flush(&mut self, cx: &mut Context) -> Poll<Result<(), AnyError>>;
}
impl DenoAsyncWrite for StreamResource {
@ -315,7 +316,7 @@ impl DenoAsyncWrite for StreamResource {
&mut self,
cx: &mut Context,
buf: &[u8],
) -> Poll<Result<usize, ErrBox>> {
) -> Poll<Result<usize, AnyError>> {
use StreamResource::*;
let f: &mut dyn UnpinAsyncWrite = match self {
FsFile(Some((f, _))) => f,
@ -326,14 +327,14 @@ impl DenoAsyncWrite for StreamResource {
ClientTlsStream(f) => f,
ServerTlsStream(f) => f,
ChildStdin(f) => f,
_ => return Err(ErrBox::bad_resource_id()).into(),
_ => return Err(bad_resource_id()).into(),
};
let v = ready!(Pin::new(f).poll_write(cx, buf))?;
Ok(v).into()
}
fn poll_flush(&mut self, cx: &mut Context) -> Poll<Result<(), ErrBox>> {
fn poll_flush(&mut self, cx: &mut Context) -> Poll<Result<(), AnyError>> {
use StreamResource::*;
let f: &mut dyn UnpinAsyncWrite = match self {
FsFile(Some((f, _))) => f,
@ -344,14 +345,14 @@ impl DenoAsyncWrite for StreamResource {
ClientTlsStream(f) => f,
ServerTlsStream(f) => f,
ChildStdin(f) => f,
_ => return Err(ErrBox::bad_resource_id()).into(),
_ => return Err(bad_resource_id()).into(),
};
ready!(Pin::new(f).poll_flush(cx))?;
Ok(()).into()
}
fn poll_close(&mut self, _cx: &mut Context) -> Poll<Result<(), ErrBox>> {
fn poll_close(&mut self, _cx: &mut Context) -> Poll<Result<(), AnyError>> {
unimplemented!()
}
}
@ -378,11 +379,9 @@ pub fn op_write(
std_file
.write(&zero_copy[0])
.map(|nwritten: usize| nwritten as i32)
.map_err(ErrBox::from)
}
Err(_) => {
Err(ErrBox::type_error("sync read not allowed on this resource"))
.map_err(AnyError::from)
}
Err(_) => Err(type_error("sync read not allowed on this resource")),
})
})
} else {
@ -394,7 +393,7 @@ pub fn op_write(
let resource_holder = state
.resource_table
.get_mut::<StreamResourceHolder>(rid as u32)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
resource_holder.resource.poll_write(cx, &zero_copy)
})
.await?;
@ -408,7 +407,7 @@ pub fn op_write(
let resource_holder = state
.resource_table
.get_mut::<StreamResourceHolder>(rid as u32)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
resource_holder.resource.poll_flush(cx)
})
.await?;
@ -431,10 +430,11 @@ pub fn std_file_resource<F, T>(
state: &mut OpState,
rid: u32,
mut f: F,
) -> Result<T, ErrBox>
) -> Result<T, AnyError>
where
F:
FnMut(Result<&mut std::fs::File, &mut StreamResource>) -> Result<T, ErrBox>,
F: FnMut(
Result<&mut std::fs::File, &mut StreamResource>,
) -> Result<T, AnyError>,
{
// First we look up the rid in the resource table.
let mut r = state.resource_table.get_mut::<StreamResourceHolder>(rid);
@ -463,16 +463,16 @@ where
// some operation is in-flight.
resource_holder.resource =
StreamResource::FsFile(Some((tokio_file, metadata)));
Err(ErrBox::resource_unavailable())
Err(resource_unavailable())
}
}
} else {
Err(ErrBox::resource_unavailable())
Err(resource_unavailable())
}
}
_ => f(Err(&mut resource_holder.resource)),
}
} else {
Err(ErrBox::bad_resource_id())
Err(bad_resource_id())
}
}

View file

@ -31,10 +31,10 @@ pub mod websocket;
pub mod worker_host;
use crate::metrics::metrics_op;
use deno_core::error::AnyError;
use deno_core::json_op_async;
use deno_core::json_op_sync;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::JsRuntime;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
@ -46,14 +46,14 @@ use std::rc::Rc;
pub fn reg_json_async<F, R>(rt: &mut JsRuntime, name: &'static str, op_fn: F)
where
F: Fn(Rc<RefCell<OpState>>, Value, BufVec) -> R + 'static,
R: Future<Output = Result<Value, ErrBox>> + 'static,
R: Future<Output = Result<Value, AnyError>> + 'static,
{
rt.register_op(name, metrics_op(json_op_async(op_fn)));
}
pub fn reg_json_sync<F>(rt: &mut JsRuntime, name: &'static str, op_fn: F)
where
F: Fn(&mut OpState, Value, &mut [ZeroCopyBuf]) -> Result<Value, ErrBox>
F: Fn(&mut OpState, Value, &mut [ZeroCopyBuf]) -> Result<Value, AnyError>
+ 'static,
{
rt.register_op(name, metrics_op(json_op_sync(op_fn)));

View file

@ -1,9 +1,15 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use crate::ops::io::{StreamResource, StreamResourceHolder};
use crate::ops::io::StreamResource;
use crate::ops::io::StreamResourceHolder;
use crate::resolve_addr::resolve_addr;
use deno_core::error::bad_resource;
use deno_core::error::bad_resource_id;
use deno_core::error::custom_error;
use deno_core::error::generic_error;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use futures::future::poll_fn;
@ -21,6 +27,8 @@ use tokio::net::UdpSocket;
#[cfg(unix)]
use super::net_unix;
#[cfg(unix)]
use std::path::Path;
pub fn init(rt: &mut deno_core::JsRuntime) {
super::reg_json_async(rt, "op_accept", op_accept);
@ -41,7 +49,7 @@ async fn accept_tcp(
state: Rc<RefCell<OpState>>,
args: AcceptArgs,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let rid = args.rid as u32;
let accept_fut = poll_fn(|cx| {
@ -49,9 +57,9 @@ async fn accept_tcp(
let listener_resource = state
.resource_table
.get_mut::<TcpListenerResource>(rid)
.ok_or_else(|| ErrBox::bad_resource("Listener has been closed"))?;
.ok_or_else(|| bad_resource("Listener has been closed"))?;
let listener = &mut listener_resource.listener;
match listener.poll_accept(cx).map_err(ErrBox::from) {
match listener.poll_accept(cx).map_err(AnyError::from) {
Poll::Ready(Ok((stream, addr))) => {
listener_resource.untrack_task();
Poll::Ready(Ok((stream, addr)))
@ -96,13 +104,13 @@ async fn op_accept(
state: Rc<RefCell<OpState>>,
args: Value,
bufs: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: AcceptArgs = serde_json::from_value(args)?;
match args.transport.as_str() {
"tcp" => accept_tcp(state, args, bufs).await,
#[cfg(unix)]
"unix" => net_unix::accept_unix(state, args, bufs).await,
_ => Err(ErrBox::error(format!(
_ => Err(generic_error(format!(
"Unsupported transport protocol {}",
args.transport
))),
@ -119,7 +127,7 @@ async fn receive_udp(
state: Rc<RefCell<OpState>>,
args: ReceiveArgs,
zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
assert_eq!(zero_copy.len(), 1, "Invalid number of arguments");
let mut zero_copy = zero_copy[0].clone();
@ -130,11 +138,11 @@ async fn receive_udp(
let resource = state
.resource_table
.get_mut::<UdpSocketResource>(rid)
.ok_or_else(|| ErrBox::bad_resource("Socket has been closed"))?;
.ok_or_else(|| bad_resource("Socket has been closed"))?;
let socket = &mut resource.socket;
socket
.poll_recv_from(cx, &mut zero_copy)
.map_err(ErrBox::from)
.map_err(AnyError::from)
});
let (size, remote_addr) = receive_fut.await?;
Ok(json!({
@ -151,7 +159,7 @@ async fn op_datagram_receive(
state: Rc<RefCell<OpState>>,
args: Value,
zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
assert_eq!(zero_copy.len(), 1, "Invalid number of arguments");
let args: ReceiveArgs = serde_json::from_value(args)?;
@ -159,7 +167,7 @@ async fn op_datagram_receive(
"udp" => receive_udp(state, args, zero_copy).await,
#[cfg(unix)]
"unixpacket" => net_unix::receive_unix_packet(state, args, zero_copy).await,
_ => Err(ErrBox::error(format!(
_ => Err(generic_error(format!(
"Unsupported transport protocol {}",
args.transport
))),
@ -178,7 +186,7 @@ async fn op_datagram_send(
state: Rc<RefCell<OpState>>,
args: Value,
zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
assert_eq!(zero_copy.len(), 1, "Invalid number of arguments");
let zero_copy = zero_copy[0].clone();
let cli_state = super::cli_state2(&state);
@ -196,12 +204,12 @@ async fn op_datagram_send(
let resource = state
.resource_table
.get_mut::<UdpSocketResource>(rid as u32)
.ok_or_else(|| ErrBox::bad_resource("Socket has been closed"))?;
.ok_or_else(|| bad_resource("Socket has been closed"))?;
resource
.socket
.poll_send_to(cx, &zero_copy, &addr)
.map_ok(|byte_length| json!(byte_length))
.map_err(ErrBox::from)
.map_err(AnyError::from)
})
.await
}
@ -211,13 +219,15 @@ async fn op_datagram_send(
transport,
transport_args: ArgsEnum::Unix(args),
} if transport == "unixpacket" => {
let address_path = net_unix::Path::new(&args.path);
let address_path = Path::new(&args.path);
cli_state.check_read(&address_path)?;
let mut state = state.borrow_mut();
let resource = state
.resource_table
.get_mut::<net_unix::UnixDatagramResource>(rid as u32)
.ok_or_else(|| ErrBox::new("NotConnected", "Socket has been closed"))?;
.ok_or_else(|| {
custom_error("NotConnected", "Socket has been closed")
})?;
let socket = &mut resource.socket;
let byte_length = socket
.send_to(&zero_copy, &resource.local_addr.as_pathname().unwrap())
@ -225,7 +235,7 @@ async fn op_datagram_send(
Ok(json!(byte_length))
}
_ => Err(ErrBox::type_error("Wrong argument format!")),
_ => Err(type_error("Wrong argument format!")),
}
}
@ -240,7 +250,7 @@ async fn op_connect(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state2(&state);
match serde_json::from_value(args)? {
ConnectArgs {
@ -279,12 +289,11 @@ async fn op_connect(
transport,
transport_args: ArgsEnum::Unix(args),
} if transport == "unix" => {
let address_path = net_unix::Path::new(&args.path);
let address_path = Path::new(&args.path);
cli_state.check_unstable("Deno.connect");
cli_state.check_read(&address_path)?;
let path = args.path;
let unix_stream =
net_unix::UnixStream::connect(net_unix::Path::new(&path)).await?;
let unix_stream = net_unix::UnixStream::connect(Path::new(&path)).await?;
let local_addr = unix_stream.local_addr()?;
let remote_addr = unix_stream.peer_addr()?;
@ -307,7 +316,7 @@ async fn op_connect(
}
}))
}
_ => Err(ErrBox::type_error("Wrong argument format!")),
_ => Err(type_error("Wrong argument format!")),
}
}
@ -321,7 +330,7 @@ fn op_shutdown(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
super::cli_state(state).check_unstable("Deno.shutdown");
let args: ShutdownArgs = serde_json::from_value(args)?;
@ -338,7 +347,7 @@ fn op_shutdown(
let resource_holder = state
.resource_table
.get_mut::<StreamResourceHolder>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
match resource_holder.resource {
StreamResource::TcpStream(Some(ref mut stream)) => {
TcpStream::shutdown(stream, shutdown_mode)?;
@ -347,7 +356,7 @@ fn op_shutdown(
StreamResource::UnixStream(ref mut stream) => {
net_unix::UnixStream::shutdown(stream, shutdown_mode)?;
}
_ => return Err(ErrBox::bad_resource_id()),
_ => return Err(bad_resource_id()),
}
Ok(json!({}))
@ -371,13 +380,13 @@ impl TcpListenerResource {
/// can be notified when listener is closed.
///
/// Throws an error if another task is already tracked.
pub fn track_task(&mut self, cx: &Context) -> Result<(), ErrBox> {
pub fn track_task(&mut self, cx: &Context) -> Result<(), AnyError> {
// Currently, we only allow tracking a single accept task for a listener.
// This might be changed in the future with multiple workers.
// Caveat: TcpListener by itself also only tracks an accept task at a time.
// See https://github.com/tokio-rs/tokio/issues/846#issuecomment-454208883
if self.waker.is_some() {
return Err(ErrBox::new("Busy", "Another accept task is ongoing"));
return Err(custom_error("Busy", "Another accept task is ongoing"));
}
let waker = futures::task::AtomicWaker::new();
@ -430,7 +439,7 @@ struct ListenArgs {
fn listen_tcp(
state: &mut OpState,
addr: SocketAddr,
) -> Result<(u32, SocketAddr), ErrBox> {
) -> Result<(u32, SocketAddr), AnyError> {
let std_listener = std::net::TcpListener::bind(&addr)?;
let listener = TcpListener::from_std(std_listener)?;
let local_addr = listener.local_addr()?;
@ -449,7 +458,7 @@ fn listen_tcp(
fn listen_udp(
state: &mut OpState,
addr: SocketAddr,
) -> Result<(u32, SocketAddr), ErrBox> {
) -> Result<(u32, SocketAddr), AnyError> {
let std_socket = std::net::UdpSocket::bind(&addr)?;
let socket = UdpSocket::from_std(std_socket)?;
let local_addr = socket.local_addr()?;
@ -465,7 +474,7 @@ fn op_listen(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
match serde_json::from_value(args)? {
ListenArgs {
@ -504,7 +513,7 @@ fn op_listen(
transport,
transport_args: ArgsEnum::Unix(args),
} if transport == "unix" || transport == "unixpacket" => {
let address_path = net_unix::Path::new(&args.path);
let address_path = Path::new(&args.path);
{
if transport == "unix" {
cli_state.check_unstable("Deno.listen");
@ -534,6 +543,6 @@ fn op_listen(
}))
}
#[cfg(unix)]
_ => Err(ErrBox::type_error("Wrong argument format!")),
_ => Err(type_error("Wrong argument format!")),
}
}

View file

@ -2,8 +2,9 @@ use crate::ops::io::StreamResource;
use crate::ops::io::StreamResourceHolder;
use crate::ops::net::AcceptArgs;
use crate::ops::net::ReceiveArgs;
use deno_core::error::bad_resource;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use futures::future::poll_fn;
use serde_derive::Deserialize;
@ -11,7 +12,7 @@ use serde_json::Value;
use std::cell::RefCell;
use std::fs::remove_file;
use std::os::unix;
pub use std::path::Path;
use std::path::Path;
use std::rc::Rc;
use std::task::Poll;
use tokio::net::UnixDatagram;
@ -36,7 +37,7 @@ pub(crate) async fn accept_unix(
state: Rc<RefCell<OpState>>,
args: AcceptArgs,
_bufs: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let rid = args.rid as u32;
let accept_fut = poll_fn(|cx| {
@ -44,7 +45,7 @@ pub(crate) async fn accept_unix(
let listener_resource = state
.resource_table
.get_mut::<UnixListenerResource>(rid)
.ok_or_else(|| ErrBox::bad_resource("Listener has been closed"))?;
.ok_or_else(|| bad_resource("Listener has been closed"))?;
let listener = &mut listener_resource.listener;
use futures::StreamExt;
match listener.poll_next_unpin(cx) {
@ -58,7 +59,7 @@ pub(crate) async fn accept_unix(
Poll::Pending
}
}
.map_err(ErrBox::from)
.map_err(AnyError::from)
});
let unix_stream = accept_fut.await?;
@ -88,7 +89,7 @@ pub(crate) async fn receive_unix_packet(
state: Rc<RefCell<OpState>>,
args: ReceiveArgs,
bufs: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
assert_eq!(bufs.len(), 1, "Invalid number of arguments");
let rid = args.rid as u32;
@ -98,7 +99,7 @@ pub(crate) async fn receive_unix_packet(
let resource = state
.resource_table
.get_mut::<UnixDatagramResource>(rid)
.ok_or_else(|| ErrBox::bad_resource("Socket has been closed"))?;
.ok_or_else(|| bad_resource("Socket has been closed"))?;
let (size, remote_addr) = resource.socket.recv_from(&mut buf).await?;
Ok(json!({
"size": size,
@ -112,7 +113,7 @@ pub(crate) async fn receive_unix_packet(
pub fn listen_unix(
state: &mut OpState,
addr: &Path,
) -> Result<(u32, unix::net::SocketAddr), ErrBox> {
) -> Result<(u32, unix::net::SocketAddr), AnyError> {
if addr.exists() {
remove_file(&addr).unwrap();
}
@ -129,7 +130,7 @@ pub fn listen_unix(
pub fn listen_unix_packet(
state: &mut OpState,
addr: &Path,
) -> Result<(u32, unix::net::SocketAddr), ErrBox> {
) -> Result<(u32, unix::net::SocketAddr), AnyError> {
if addr.exists() {
remove_file(&addr).unwrap();
}

View file

@ -1,6 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::ErrBox;
use deno_core::error::AnyError;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use serde_derive::Deserialize;
@ -26,7 +26,7 @@ fn op_exec_path(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let current_exe = env::current_exe().unwrap();
let cli_state = super::cli_state(state);
cli_state.check_read_blind(&current_exe, "exec_path")?;
@ -47,7 +47,7 @@ fn op_set_env(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: SetEnv = serde_json::from_value(args)?;
let cli_state = super::cli_state(state);
cli_state.check_env()?;
@ -59,7 +59,7 @@ fn op_env(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
cli_state.check_env()?;
let v = env::vars().collect::<HashMap<String, String>>();
@ -75,7 +75,7 @@ fn op_get_env(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: GetEnv = serde_json::from_value(args)?;
let cli_state = super::cli_state(state);
cli_state.check_env()?;
@ -95,7 +95,7 @@ fn op_delete_env(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: DeleteEnv = serde_json::from_value(args)?;
let cli_state = super::cli_state(state);
cli_state.check_env()?;
@ -112,7 +112,7 @@ fn op_exit(
_state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: Exit = serde_json::from_value(args)?;
std::process::exit(args.code)
}
@ -121,7 +121,7 @@ fn op_loadavg(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.loadavg");
cli_state.check_env()?;
@ -135,7 +135,7 @@ fn op_hostname(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.hostname");
cli_state.check_env()?;
@ -147,7 +147,7 @@ fn op_os_release(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.osRelease");
cli_state.check_env()?;
@ -159,7 +159,7 @@ fn op_system_memory_info(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.systemMemoryInfo");
cli_state.check_env()?;

View file

@ -1,6 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::ErrBox;
use deno_core::error::custom_error;
use deno_core::error::AnyError;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use serde_derive::Deserialize;
@ -24,7 +25,7 @@ pub fn op_query_permission(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: PermissionArgs = serde_json::from_value(args)?;
let cli_state = super::cli_state(state);
let permissions = cli_state.permissions.borrow();
@ -38,7 +39,7 @@ pub fn op_query_permission(
"plugin" => permissions.query_plugin(),
"hrtime" => permissions.query_hrtime(),
n => {
return Err(ErrBox::new(
return Err(custom_error(
"ReferenceError",
format!("No such permission name: {}", n),
))
@ -51,7 +52,7 @@ pub fn op_revoke_permission(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: PermissionArgs = serde_json::from_value(args)?;
let cli_state = super::cli_state(state);
let mut permissions = cli_state.permissions.borrow_mut();
@ -65,7 +66,7 @@ pub fn op_revoke_permission(
"plugin" => permissions.revoke_plugin(),
"hrtime" => permissions.revoke_hrtime(),
n => {
return Err(ErrBox::new(
return Err(custom_error(
"ReferenceError",
format!("No such permission name: {}", n),
))
@ -78,7 +79,7 @@ pub fn op_request_permission(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: PermissionArgs = serde_json::from_value(args)?;
let cli_state = super::cli_state(state);
let permissions = &mut cli_state.permissions.borrow_mut();
@ -92,7 +93,7 @@ pub fn op_request_permission(
"plugin" => permissions.request_plugin(),
"hrtime" => permissions.request_hrtime(),
n => {
return Err(ErrBox::new(
return Err(custom_error(
"ReferenceError",
format!("No such permission name: {}", n),
))

View file

@ -1,9 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use crate::metrics::metrics_op;
use deno_core::error::AnyError;
use deno_core::plugin_api;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::JsRuntime;
use deno_core::Op;
use deno_core::OpAsyncFuture;
@ -35,7 +35,7 @@ pub fn op_open_plugin(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: OpenPluginArgs = serde_json::from_value(args)?;
let filename = PathBuf::from(&args.filename);

View file

@ -2,8 +2,10 @@
use super::io::{std_file_resource, StreamResource, StreamResourceHolder};
use crate::signal::kill;
use deno_core::error::bad_resource_id;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use futures::future::poll_fn;
@ -23,19 +25,22 @@ pub fn init(rt: &mut deno_core::JsRuntime) {
super::reg_json_sync(rt, "op_kill", op_kill);
}
fn clone_file(state: &mut OpState, rid: u32) -> Result<std::fs::File, ErrBox> {
fn clone_file(
state: &mut OpState,
rid: u32,
) -> Result<std::fs::File, AnyError> {
std_file_resource(state, rid, move |r| match r {
Ok(std_file) => std_file.try_clone().map_err(ErrBox::from),
Err(_) => Err(ErrBox::bad_resource_id()),
Ok(std_file) => std_file.try_clone().map_err(AnyError::from),
Err(_) => Err(bad_resource_id()),
})
}
fn subprocess_stdio_map(s: &str) -> Result<std::process::Stdio, ErrBox> {
fn subprocess_stdio_map(s: &str) -> Result<std::process::Stdio, AnyError> {
match s {
"inherit" => Ok(std::process::Stdio::inherit()),
"piped" => Ok(std::process::Stdio::piped()),
"null" => Ok(std::process::Stdio::null()),
_ => Err(ErrBox::type_error("Invalid resource for stdio")),
_ => Err(type_error("Invalid resource for stdio")),
}
}
@ -61,7 +66,7 @@ fn op_run(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let run_args: RunArgs = serde_json::from_value(args)?;
super::cli_state(state).check_run()?;
@ -169,7 +174,7 @@ async fn op_run_status(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: RunStatusArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
@ -180,9 +185,9 @@ async fn op_run_status(
let child_resource = state
.resource_table
.get_mut::<ChildResource>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
let child = &mut child_resource.child;
child.poll_unpin(cx).map_err(ErrBox::from)
child.poll_unpin(cx).map_err(AnyError::from)
})
.await?;
@ -215,7 +220,7 @@ fn op_kill(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
cli_state.check_unstable("Deno.kill");
cli_state.check_run()?;

View file

@ -1,6 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::ErrBox;
use deno_core::error::AnyError;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use rand::thread_rng;
@ -15,7 +15,7 @@ fn op_get_random_values(
state: &mut OpState,
_args: Value,
zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
assert_eq!(zero_copy.len(), 1);
let cli_state = super::cli_state(state);
if let Some(seeded_rng) = &cli_state.seeded_rng {

View file

@ -2,8 +2,9 @@
use crate::repl;
use crate::repl::Repl;
use deno_core::error::bad_resource_id;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use serde_derive::Deserialize;
@ -30,7 +31,7 @@ fn op_repl_start(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ReplStartArgs = serde_json::from_value(args)?;
debug!("op_repl_start {}", args.history_file);
let history_path = {
@ -53,7 +54,7 @@ async fn op_repl_readline(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ReplReadlineArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
let prompt = args.prompt;
@ -63,7 +64,7 @@ async fn op_repl_readline(
let resource = state
.resource_table
.get::<ReplResource>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
resource.0.clone()
};
tokio::task::spawn_blocking(move || {

View file

@ -1,6 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::ErrBox;
use deno_core::error::bad_resource_id;
use deno_core::error::AnyError;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use serde_derive::Deserialize;
@ -15,7 +16,7 @@ fn op_resources(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let serialized_resources = state.resource_table.entries();
Ok(json!(serialized_resources))
}
@ -25,7 +26,7 @@ fn op_close(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
#[derive(Deserialize)]
struct CloseArgs {
rid: i32,
@ -34,6 +35,6 @@ fn op_close(
state
.resource_table
.close(args.rid as u32)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
Ok(json!({}))
}

View file

@ -3,7 +3,7 @@
use crate::colors;
use crate::version;
use crate::DenoSubcommand;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use deno_core::ModuleSpecifier;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
@ -20,7 +20,7 @@ fn op_start(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let gs = &super::cli_state(state).global_state;
Ok(json!({
@ -45,7 +45,7 @@ fn op_main_module(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
let main = &cli_state.main_module.to_string();
let main_url = ModuleSpecifier::resolve_url_or_path(&main)?;
@ -60,7 +60,7 @@ fn op_metrics(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
let m = &cli_state.metrics.borrow();

View file

@ -4,8 +4,8 @@ use crate::futures::FutureExt;
use crate::tsc::runtime_bundle;
use crate::tsc::runtime_compile;
use crate::tsc::runtime_transpile;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use serde_derive::Deserialize;
use serde_json::Value;
@ -31,7 +31,7 @@ async fn op_compile(
state: Rc<RefCell<OpState>>,
args: Value,
_data: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state2(&state);
cli_state.check_unstable("Deno.compile");
let args: CompileArgs = serde_json::from_value(args)?;
@ -70,7 +70,7 @@ async fn op_transpile(
state: Rc<RefCell<OpState>>,
args: Value,
_data: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state2(&state);
cli_state.check_unstable("Deno.transpile");
let args: TranspileArgs = serde_json::from_value(args)?;

View file

@ -1,13 +1,15 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use serde_json::Value;
use std::cell::RefCell;
use std::rc::Rc;
#[cfg(unix)]
use deno_core::error::bad_resource_id;
#[cfg(unix)]
use futures::future::poll_fn;
#[cfg(unix)]
@ -45,7 +47,7 @@ fn op_signal_bind(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
super::cli_state(state).check_unstable("Deno.signal");
let args: BindSignalArgs = serde_json::from_value(args)?;
let rid = state.resource_table.add(
@ -65,7 +67,7 @@ async fn op_signal_poll(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
super::cli_state2(&state).check_unstable("Deno.signal");
let args: SignalArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
@ -89,7 +91,7 @@ pub fn op_signal_unbind(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
super::cli_state(state).check_unstable("Deno.signal");
let args: SignalArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
@ -104,7 +106,7 @@ pub fn op_signal_unbind(
state
.resource_table
.close(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
Ok(json!({}))
}
@ -113,7 +115,7 @@ pub fn op_signal_bind(
_state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
unimplemented!();
}
@ -122,7 +124,7 @@ fn op_signal_unbind(
_state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
unimplemented!();
}
@ -131,6 +133,6 @@ async fn op_signal_poll(
_state: Rc<RefCell<OpState>>,
_args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
unimplemented!();
}

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use futures::future::FutureExt;
@ -22,7 +22,7 @@ fn op_global_timer_stop(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
cli_state.global_timer.borrow_mut().cancel();
Ok(json!({}))
@ -37,7 +37,7 @@ async fn op_global_timer(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: GlobalTimerArgs = serde_json::from_value(args)?;
let val = args.timeout;
@ -61,7 +61,7 @@ fn op_now(
state: &mut OpState,
_args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
let seconds = cli_state.start_time.elapsed().as_secs();
let mut subsec_nanos = cli_state.start_time.elapsed().subsec_nanos();

View file

@ -2,8 +2,11 @@
use super::io::{StreamResource, StreamResourceHolder};
use crate::resolve_addr::resolve_addr;
use deno_core::error::bad_resource;
use deno_core::error::bad_resource_id;
use deno_core::error::custom_error;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
use futures::future::poll_fn;
@ -59,7 +62,7 @@ async fn op_start_tls(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: StartTLSArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
let cert_file = args.cert_file.clone();
@ -80,7 +83,7 @@ async fn op_start_tls(
let mut state_ = state.borrow_mut();
match state_.resource_table.remove::<StreamResourceHolder>(rid) {
Some(resource) => *resource,
None => return Err(ErrBox::bad_resource_id()),
None => return Err(bad_resource_id()),
}
};
@ -128,7 +131,7 @@ async fn op_start_tls(
}
}))
} else {
Err(ErrBox::bad_resource_id())
Err(bad_resource_id())
}
}
@ -136,7 +139,7 @@ async fn op_connect_tls(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ConnectTLSArgs = serde_json::from_value(args)?;
let cert_file = args.cert_file.clone();
{
@ -192,31 +195,31 @@ async fn op_connect_tls(
}))
}
fn load_certs(path: &str) -> Result<Vec<Certificate>, ErrBox> {
fn load_certs(path: &str) -> Result<Vec<Certificate>, AnyError> {
let cert_file = File::open(path)?;
let reader = &mut BufReader::new(cert_file);
let certs = certs(reader)
.map_err(|_| ErrBox::new("InvalidData", "Unable to decode certificate"))?;
.map_err(|_| custom_error("InvalidData", "Unable to decode certificate"))?;
if certs.is_empty() {
let e = ErrBox::new("InvalidData", "No certificates found in cert file");
let e = custom_error("InvalidData", "No certificates found in cert file");
return Err(e);
}
Ok(certs)
}
fn key_decode_err() -> ErrBox {
ErrBox::new("InvalidData", "Unable to decode key")
fn key_decode_err() -> AnyError {
custom_error("InvalidData", "Unable to decode key")
}
fn key_not_found_err() -> ErrBox {
ErrBox::new("InvalidData", "No keys found in key file")
fn key_not_found_err() -> AnyError {
custom_error("InvalidData", "No keys found in key file")
}
/// Starts with -----BEGIN RSA PRIVATE KEY-----
fn load_rsa_keys(path: &str) -> Result<Vec<PrivateKey>, ErrBox> {
fn load_rsa_keys(path: &str) -> Result<Vec<PrivateKey>, AnyError> {
let key_file = File::open(path)?;
let reader = &mut BufReader::new(key_file);
let keys = rsa_private_keys(reader).map_err(|_| key_decode_err())?;
@ -224,14 +227,14 @@ fn load_rsa_keys(path: &str) -> Result<Vec<PrivateKey>, ErrBox> {
}
/// Starts with -----BEGIN PRIVATE KEY-----
fn load_pkcs8_keys(path: &str) -> Result<Vec<PrivateKey>, ErrBox> {
fn load_pkcs8_keys(path: &str) -> Result<Vec<PrivateKey>, AnyError> {
let key_file = File::open(path)?;
let reader = &mut BufReader::new(key_file);
let keys = pkcs8_private_keys(reader).map_err(|_| key_decode_err())?;
Ok(keys)
}
fn load_keys(path: &str) -> Result<Vec<PrivateKey>, ErrBox> {
fn load_keys(path: &str) -> Result<Vec<PrivateKey>, AnyError> {
let path = path.to_string();
let mut keys = load_rsa_keys(&path)?;
@ -265,13 +268,13 @@ impl TlsListenerResource {
/// can be notified when listener is closed.
///
/// Throws an error if another task is already tracked.
pub fn track_task(&mut self, cx: &Context) -> Result<(), ErrBox> {
pub fn track_task(&mut self, cx: &Context) -> Result<(), AnyError> {
// Currently, we only allow tracking a single accept task for a listener.
// This might be changed in the future with multiple workers.
// Caveat: TcpListener by itself also only tracks an accept task at a time.
// See https://github.com/tokio-rs/tokio/issues/846#issuecomment-454208883
if self.waker.is_some() {
return Err(ErrBox::new("Busy", "Another accept task is ongoing"));
return Err(custom_error("Busy", "Another accept task is ongoing"));
}
let waker = futures::task::AtomicWaker::new();
@ -308,7 +311,7 @@ fn op_listen_tls(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: ListenTlsArgs = serde_json::from_value(args)?;
assert_eq!(args.transport, "tcp");
@ -359,7 +362,7 @@ async fn op_accept_tls(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: AcceptTlsArgs = serde_json::from_value(args)?;
let rid = args.rid as u32;
let accept_fut = poll_fn(|cx| {
@ -367,9 +370,9 @@ async fn op_accept_tls(
let listener_resource = state
.resource_table
.get_mut::<TlsListenerResource>(rid)
.ok_or_else(|| ErrBox::bad_resource("Listener has been closed"))?;
.ok_or_else(|| bad_resource("Listener has been closed"))?;
let listener = &mut listener_resource.listener;
match listener.poll_accept(cx).map_err(ErrBox::from) {
match listener.poll_accept(cx).map_err(AnyError::from) {
Poll::Ready(Ok((stream, addr))) => {
listener_resource.untrack_task();
Poll::Ready(Ok((stream, addr)))
@ -392,7 +395,7 @@ async fn op_accept_tls(
let resource = state_
.resource_table
.get::<TlsListenerResource>(rid)
.ok_or_else(ErrBox::bad_resource_id)
.ok_or_else(bad_resource_id)
.expect("Can't find tls listener");
resource.tls_acceptor.clone()
};

View file

@ -1,15 +1,25 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use super::io::std_file_resource;
use super::io::{StreamResource, StreamResourceHolder};
use deno_core::ErrBox;
use super::io::StreamResource;
use super::io::StreamResourceHolder;
use deno_core::error::bad_resource_id;
use deno_core::error::last_os_error;
use deno_core::error::resource_unavailable;
use deno_core::error::AnyError;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
#[cfg(unix)]
use nix::sys::termios;
use serde_derive::{Deserialize, Serialize};
use serde_derive::Deserialize;
use serde_derive::Serialize;
use serde_json::Value;
#[cfg(unix)]
use deno_core::error::not_supported;
#[cfg(unix)]
use nix::sys::termios;
#[cfg(windows)]
use deno_core::error::custom_error;
#[cfg(windows)]
use winapi::shared::minwindef::DWORD;
#[cfg(windows)]
@ -22,15 +32,15 @@ const RAW_MODE_MASK: DWORD = wincon::ENABLE_LINE_INPUT
#[cfg(windows)]
fn get_windows_handle(
f: &std::fs::File,
) -> Result<std::os::windows::io::RawHandle, ErrBox> {
) -> Result<std::os::windows::io::RawHandle, AnyError> {
use std::os::windows::io::AsRawHandle;
use winapi::um::handleapi;
let handle = f.as_raw_handle();
if handle == handleapi::INVALID_HANDLE_VALUE {
return Err(ErrBox::last_os_error());
return Err(last_os_error());
} else if handle.is_null() {
return Err(ErrBox::new("ReferenceError", "null handle"));
return Err(custom_error("ReferenceError", "null handle"));
}
Ok(handle)
}
@ -51,7 +61,7 @@ fn op_set_raw(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
super::cli_state(state).check_unstable("Deno.setRaw");
let args: SetRawArgs = serde_json::from_value(args)?;
@ -72,7 +82,7 @@ fn op_set_raw(
let resource_holder =
state.resource_table.get_mut::<StreamResourceHolder>(rid);
if resource_holder.is_none() {
return Err(ErrBox::bad_resource_id());
return Err(bad_resource_id());
}
let resource_holder = resource_holder.unwrap();
@ -97,28 +107,28 @@ fn op_set_raw(
// some operation is in-flight.
resource_holder.resource =
StreamResource::FsFile(Some((tokio_file, metadata)));
return Err(ErrBox::resource_unavailable());
return Err(resource_unavailable());
}
}
} else {
return Err(ErrBox::resource_unavailable());
return Err(resource_unavailable());
}
}
_ => {
return Err(ErrBox::bad_resource_id());
return Err(bad_resource_id());
}
};
if handle == handleapi::INVALID_HANDLE_VALUE {
return Err(ErrBox::last_os_error());
return Err(last_os_error());
} else if handle.is_null() {
return Err(ErrBox::new("ReferenceError", "null handle"));
return Err(custom_error("ReferenceError", "null handle"));
}
let mut original_mode: DWORD = 0;
if unsafe { consoleapi::GetConsoleMode(handle, &mut original_mode) }
== FALSE
{
return Err(ErrBox::last_os_error());
return Err(last_os_error());
}
let new_mode = if is_raw {
original_mode & !RAW_MODE_MASK
@ -126,7 +136,7 @@ fn op_set_raw(
original_mode | RAW_MODE_MASK
};
if unsafe { consoleapi::SetConsoleMode(handle, new_mode) } == FALSE {
return Err(ErrBox::last_os_error());
return Err(last_os_error());
}
Ok(json!({}))
@ -138,7 +148,7 @@ fn op_set_raw(
let resource_holder =
state.resource_table.get_mut::<StreamResourceHolder>(rid);
if resource_holder.is_none() {
return Err(ErrBox::bad_resource_id());
return Err(bad_resource_id());
}
if is_raw {
@ -150,11 +160,9 @@ fn op_set_raw(
StreamResource::FsFile(Some((f, ref mut metadata))) => {
(f.as_raw_fd(), &mut metadata.tty.mode)
}
StreamResource::FsFile(None) => {
return Err(ErrBox::resource_unavailable())
}
StreamResource::FsFile(None) => return Err(resource_unavailable()),
_ => {
return Err(ErrBox::not_supported());
return Err(not_supported());
}
};
@ -195,10 +203,10 @@ fn op_set_raw(
(f.as_raw_fd(), &mut metadata.tty.mode)
}
StreamResource::FsFile(None) => {
return Err(ErrBox::resource_unavailable());
return Err(resource_unavailable());
}
_ => {
return Err(ErrBox::bad_resource_id());
return Err(bad_resource_id());
}
};
@ -220,7 +228,7 @@ fn op_isatty(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: IsattyArgs = serde_json::from_value(args)?;
let rid = args.rid;
@ -264,7 +272,7 @@ fn op_console_size(
state: &mut OpState,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
super::cli_state(state).check_unstable("Deno.consoleSize");
let args: ConsoleSizeArgs = serde_json::from_value(args)?;
@ -286,7 +294,7 @@ fn op_console_size(
&mut bufinfo,
) == 0
{
return Err(ErrBox::last_os_error());
return Err(last_os_error());
}
Ok(ConsoleSize {
@ -304,7 +312,7 @@ fn op_console_size(
unsafe {
let mut size: libc::winsize = std::mem::zeroed();
if libc::ioctl(fd, libc::TIOCGWINSZ, &mut size as *mut _) != 0 {
return Err(ErrBox::last_os_error());
return Err(last_os_error());
}
// TODO (caspervonb) return a tuple instead
@ -315,7 +323,7 @@ fn op_console_size(
}
}
}
Err(_) => Err(ErrBox::bad_resource_id()),
Err(_) => Err(bad_resource_id()),
})?;
Ok(json!(size))

View file

@ -1,8 +1,10 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use core::task::Poll;
use deno_core::error::bad_resource_id;
use deno_core::error::type_error;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::OpState;
use futures::future::poll_fn;
use futures::StreamExt;
@ -19,9 +21,10 @@ use std::sync::Arc;
use tokio::net::TcpStream;
use tokio_rustls::{rustls::ClientConfig, TlsConnector};
use tokio_tungstenite::stream::Stream as StreamSwitcher;
use tokio_tungstenite::tungstenite::Error as TungsteniteError;
use tokio_tungstenite::tungstenite::{
handshake::client::Response, protocol::frame::coding::CloseCode,
protocol::CloseFrame, Error, Message,
protocol::CloseFrame, Message,
};
use tokio_tungstenite::{client_async, WebSocketStream};
use webpki::DNSNameRef;
@ -49,7 +52,7 @@ pub async fn op_ws_create(
state: Rc<RefCell<OpState>>,
args: Value,
_bufs: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: CreateArgs = serde_json::from_value(args)?;
let ca_file = {
let cli_state = super::cli_state2(&state);
@ -70,7 +73,7 @@ pub async fn op_ws_create(
});
let addr = format!("{}:{}", domain, port);
let try_socket = TcpStream::connect(addr).await;
let tcp_socket = match try_socket.map_err(Error::Io) {
let tcp_socket = match try_socket.map_err(TungsteniteError::Io) {
Ok(socket) => socket,
Err(_) => return Ok(json!({"success": false})),
};
@ -100,7 +103,7 @@ pub async fn op_ws_create(
let (stream, response): (WsStream, Response) =
client_async(request, socket).await.map_err(|err| {
ErrBox::type_error(format!(
type_error(format!(
"failed to connect to WebSocket: {}",
err.to_string()
))
@ -140,7 +143,7 @@ pub async fn op_ws_send(
state: Rc<RefCell<OpState>>,
args: Value,
bufs: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: SendArgs = serde_json::from_value(args)?;
let mut maybe_msg = Some(match args.text {
@ -154,11 +157,10 @@ pub async fn op_ws_send(
let stream = state
.resource_table
.get_mut::<WsStream>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
// TODO(ry) Handle errors below instead of unwrap.
// Need to map tungstenite::error::Error to ErrBox.
// Need to map `TungsteniteError` to `AnyError`.
ready!(stream.poll_ready_unpin(cx)).unwrap();
if let Some(msg) = maybe_msg.take() {
stream.start_send_unpin(msg).unwrap();
@ -182,7 +184,7 @@ pub async fn op_ws_close(
state: Rc<RefCell<OpState>>,
args: Value,
_bufs: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: CloseArgs = serde_json::from_value(args)?;
let rid = args.rid;
let mut maybe_msg = Some(Message::Close(args.code.map(|c| CloseFrame {
@ -198,11 +200,10 @@ pub async fn op_ws_close(
let stream = state
.resource_table
.get_mut::<WsStream>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
// TODO(ry) Handle errors below instead of unwrap.
// Need to map tungstenite::error::Error to ErrBox.
// Need to map `TungsteniteError` to `AnyError`.
ready!(stream.poll_ready_unpin(cx)).unwrap();
if let Some(msg) = maybe_msg.take() {
stream.start_send_unpin(msg).unwrap();
@ -225,14 +226,14 @@ pub async fn op_ws_next_event(
state: Rc<RefCell<OpState>>,
args: Value,
_bufs: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: NextEventArgs = serde_json::from_value(args)?;
poll_fn(move |cx| {
let mut state = state.borrow_mut();
let stream = state
.resource_table
.get_mut::<WsStream>(args.rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
stream
.poll_next_unpin(cx)
.map(|val| {

View file

@ -8,8 +8,8 @@ use crate::tokio_util::create_basic_runtime;
use crate::web_worker::WebWorker;
use crate::web_worker::WebWorkerHandle;
use crate::worker::WorkerEvent;
use deno_core::error::AnyError;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::ModuleSpecifier;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
@ -40,7 +40,7 @@ fn create_web_worker(
permissions: Permissions,
specifier: ModuleSpecifier,
has_deno_namespace: bool,
) -> Result<WebWorker, ErrBox> {
) -> Result<WebWorker, AnyError> {
let cli_state = crate::state::State::new_for_worker(
global_state,
Some(permissions),
@ -84,10 +84,10 @@ fn run_worker_thread(
specifier: ModuleSpecifier,
has_deno_namespace: bool,
maybe_source_code: Option<String>,
) -> Result<(JoinHandle<()>, WebWorkerHandle), ErrBox> {
) -> Result<(JoinHandle<()>, WebWorkerHandle), AnyError> {
let global_state = global_state.clone();
let (handle_sender, handle_receiver) =
std::sync::mpsc::sync_channel::<Result<WebWorkerHandle, ErrBox>>(1);
std::sync::mpsc::sync_channel::<Result<WebWorkerHandle, AnyError>>(1);
let builder =
std::thread::Builder::new().name(format!("deno-worker-{}", worker_id));
@ -177,7 +177,7 @@ fn op_create_worker(
state: &mut OpState,
args: Value,
_data: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let cli_state = super::cli_state(state);
let args: CreateWorkerArgs = serde_json::from_value(args)?;
@ -229,7 +229,7 @@ fn op_host_terminate_worker(
state: &mut OpState,
args: Value,
_data: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: WorkerArgs = serde_json::from_value(args)?;
let id = args.id as u32;
let cli_state = super::cli_state(state);
@ -298,7 +298,7 @@ async fn op_host_get_message(
state: Rc<RefCell<OpState>>,
args: Value,
_zero_copy: BufVec,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let args: WorkerArgs = serde_json::from_value(args)?;
let id = args.id as u32;
let cli_state = super::cli_state2(&state);
@ -347,7 +347,7 @@ fn op_host_post_message(
state: &mut OpState,
args: Value,
data: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
assert_eq!(data.len(), 1, "Invalid number of arguments");
let args: WorkerArgs = serde_json::from_value(args)?;
let id = args.id as u32;

View file

@ -3,7 +3,9 @@
use crate::colors;
use crate::flags::Flags;
use crate::fs::resolve_from_cwd;
use deno_core::ErrBox;
use deno_core::error::custom_error;
use deno_core::error::uri_error;
use deno_core::error::AnyError;
use serde::Deserialize;
use std::collections::HashSet;
use std::env::current_dir;
@ -32,17 +34,17 @@ pub enum PermissionState {
impl PermissionState {
/// Check the permission state.
fn check(self, msg: &str, flag_name: &str) -> Result<(), ErrBox> {
fn check(self, msg: &str, flag_name: &str) -> Result<(), AnyError> {
if self == PermissionState::Granted {
log_perm_access(msg);
return Ok(());
}
let message = format!("{}, run again with the {} flag", msg, flag_name);
Err(ErrBox::new("PermissionDenied", message))
Err(custom_error("PermissionDenied", message))
}
/// Check that the permissions represented by `other` don't escalate ours.
fn check_fork(self, other: &Self) -> Result<(), ErrBox> {
fn check_fork(self, other: &Self) -> Result<(), AnyError> {
if self == PermissionState::Denied && other != &PermissionState::Denied
|| self == PermissionState::Prompt && other == &PermissionState::Granted
{
@ -98,7 +100,7 @@ pub struct UnaryPermission<T: Eq + Hash> {
impl<T: Eq + Hash> UnaryPermission<T> {
/// Check that the permissions represented by `other` don't escalate ours.
fn check_fork(&self, other: &Self) -> Result<(), ErrBox> {
fn check_fork(&self, other: &Self) -> Result<(), AnyError> {
self.global_state.check_fork(&other.global_state)?;
if !self.granted_list.is_superset(&other.granted_list) {
return Err(permission_escalation_error());
@ -251,7 +253,7 @@ impl Permissions {
pub fn query_net_url(
&self,
url: &Option<&str>,
) -> Result<PermissionState, ErrBox> {
) -> Result<PermissionState, AnyError> {
if url.is_none() {
return Ok(self.net.global_state);
}
@ -261,7 +263,7 @@ impl Permissions {
// The url may be parsed correctly but still lack a host, i.e. "localhost:235" or "mailto:someone@somewhere.com" or "file:/1.txt"
// Note that host:port combos are parsed as scheme:path
if parsed.host().is_none() {
return Err(ErrBox::new(
return Err(custom_error(
"URIError",
"invalid urlormat: <scheme>://<host>[:port][/subpath]",
));
@ -375,7 +377,7 @@ impl Permissions {
pub fn request_net(
&mut self,
url: &Option<&str>,
) -> Result<PermissionState, ErrBox> {
) -> Result<PermissionState, AnyError> {
if let Some(url) = url {
let state = self.query_net_url(&Some(url))?;
if state == PermissionState::Prompt {
@ -487,7 +489,7 @@ impl Permissions {
pub fn revoke_net(
&mut self,
url: &Option<&str>,
) -> Result<PermissionState, ErrBox> {
) -> Result<PermissionState, AnyError> {
if let Some(url) = url {
self.net.granted_list.remove(*url);
} else {
@ -527,7 +529,7 @@ impl Permissions {
self.hrtime
}
pub fn check_read(&self, path: &Path) -> Result<(), ErrBox> {
pub fn check_read(&self, path: &Path) -> Result<(), AnyError> {
let (resolved_path, display_path) = self.resolved_and_display_path(path);
self.query_read(&Some(&resolved_path)).check(
&format!("read access to \"{}\"", display_path.display()),
@ -541,14 +543,14 @@ impl Permissions {
&self,
path: &Path,
display: &str,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let resolved_path = resolve_from_cwd(path).unwrap();
self
.query_read(&Some(&resolved_path))
.check(&format!("read access to <{}>", display), "--allow-read")
}
pub fn check_write(&self, path: &Path) -> Result<(), ErrBox> {
pub fn check_write(&self, path: &Path) -> Result<(), AnyError> {
let (resolved_path, display_path) = self.resolved_and_display_path(path);
self.query_write(&Some(&resolved_path)).check(
&format!("write access to \"{}\"", display_path.display()),
@ -556,33 +558,31 @@ impl Permissions {
)
}
pub fn check_net(&self, hostname: &str, port: u16) -> Result<(), ErrBox> {
pub fn check_net(&self, hostname: &str, port: u16) -> Result<(), AnyError> {
self.query_net(hostname, Some(port)).check(
&format!("network access to \"{}:{}\"", hostname, port),
"--allow-net",
)
}
pub fn check_net_url(&self, url: &url::Url) -> Result<(), ErrBox> {
let host = url
.host_str()
.ok_or_else(|| ErrBox::new("URIError", "missing host"))?;
pub fn check_net_url(&self, url: &url::Url) -> Result<(), AnyError> {
let host = url.host_str().ok_or_else(|| uri_error("missing host"))?;
self
.query_net(host, url.port_or_known_default())
.check(&format!("network access to \"{}\"", url), "--allow-net")
}
pub fn check_env(&self) -> Result<(), ErrBox> {
pub fn check_env(&self) -> Result<(), AnyError> {
self
.env
.check("access to environment variables", "--allow-env")
}
pub fn check_run(&self) -> Result<(), ErrBox> {
pub fn check_run(&self) -> Result<(), AnyError> {
self.run.check("access to run a subprocess", "--allow-run")
}
pub fn check_plugin(&self, path: &Path) -> Result<(), ErrBox> {
pub fn check_plugin(&self, path: &Path) -> Result<(), AnyError> {
let (_, display_path) = self.resolved_and_display_path(path);
self.plugin.check(
&format!("access to open a plugin: {}", display_path.display()),
@ -590,7 +590,7 @@ impl Permissions {
)
}
pub fn check_hrtime(&self) -> Result<(), ErrBox> {
pub fn check_hrtime(&self) -> Result<(), AnyError> {
self
.hrtime
.check("access to high precision time", "--allow-run")
@ -606,7 +606,7 @@ impl Permissions {
run: PermissionState,
plugin: PermissionState,
hrtime: PermissionState,
) -> Result<Permissions, ErrBox> {
) -> Result<Permissions, AnyError> {
self.read.check_fork(&read)?;
self.write.check_fork(&write)?;
self.net.check_fork(&net)?;
@ -716,8 +716,8 @@ fn check_host_and_port_list(
&& allowlist.contains(&format!("{}:{}", host, port.unwrap())))
}
fn permission_escalation_error() -> ErrBox {
ErrBox::new("PermissionDenied", "Arguments escalate parent permissions")
fn permission_escalation_error() -> AnyError {
custom_error("PermissionDenied", "Arguments escalate parent permissions")
}
#[cfg(test)]

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use crate::deno_dir::DenoDir;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use rustyline::Editor;
use std::fs;
use std::path::PathBuf;
@ -34,7 +34,7 @@ impl Repl {
.unwrap_or(())
}
fn save_history(&mut self) -> Result<(), ErrBox> {
fn save_history(&mut self) -> Result<(), AnyError> {
fs::create_dir_all(self.history_file.parent().unwrap())?;
self
.editor
@ -46,7 +46,7 @@ impl Repl {
})
}
pub fn readline(&mut self, prompt: &str) -> Result<String, ErrBox> {
pub fn readline(&mut self, prompt: &str) -> Result<String, AnyError> {
self
.editor
.readline(&prompt)
@ -54,7 +54,7 @@ impl Repl {
self.editor.add_history_entry(line.clone());
line
})
.map_err(ErrBox::from)
.map_err(AnyError::from)
// Forward error to TS side for processing
}

View file

@ -1,11 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::ErrBox;
use deno_core::error::AnyError;
use std::net::SocketAddr;
use std::net::ToSocketAddrs;
/// Resolve network address. Returns a future.
pub fn resolve_addr(hostname: &str, port: u16) -> Result<SocketAddr, ErrBox> {
pub fn resolve_addr(hostname: &str, port: u16) -> Result<SocketAddr, AnyError> {
// Default to localhost if given just the port. Example: ":80"
let addr: &str = if !hostname.is_empty() {
&hostname

View file

@ -1,6 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::ErrBox;
use deno_core::error::AnyError;
#[cfg(not(unix))]
use deno_core::error::last_os_error;
#[cfg(not(unix))]
use deno_core::error::type_error;
#[cfg(not(unix))]
const SIGINT: i32 = 2;
@ -20,37 +25,37 @@ use winapi::{
};
#[cfg(unix)]
pub fn kill(pid: i32, signo: i32) -> Result<(), ErrBox> {
pub fn kill(pid: i32, signo: i32) -> Result<(), AnyError> {
use nix::sys::signal::{kill as unix_kill, Signal};
use nix::unistd::Pid;
use std::convert::TryFrom;
let sig = Signal::try_from(signo)?;
unix_kill(Pid::from_raw(pid), Option::Some(sig)).map_err(ErrBox::from)
unix_kill(Pid::from_raw(pid), Option::Some(sig)).map_err(AnyError::from)
}
#[cfg(not(unix))]
pub fn kill(pid: i32, signal: i32) -> Result<(), ErrBox> {
pub fn kill(pid: i32, signal: i32) -> Result<(), AnyError> {
match signal {
SIGINT | SIGKILL | SIGTERM => {
if pid <= 0 {
return Err(ErrBox::type_error("unsupported pid"));
return Err(type_error("unsupported pid"));
}
unsafe {
let handle = OpenProcess(PROCESS_TERMINATE, 0, pid as DWORD);
if handle.is_null() {
return Err(ErrBox::last_os_error());
return Err(last_os_error());
}
if TerminateProcess(handle, 1) == 0 {
CloseHandle(handle);
return Err(ErrBox::last_os_error());
return Err(last_os_error());
}
if CloseHandle(handle) == 0 {
return Err(ErrBox::last_os_error());
return Err(last_os_error());
}
}
}
_ => {
return Err(ErrBox::type_error("unsupported signal"));
return Err(type_error("unsupported signal"));
}
}
Ok(())

View file

@ -1,5 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
//! This mod provides functions to remap a deno_core::deno_core::JsError based on a source map
//! This mod provides functions to remap a `JsError` based on a source map.
use deno_core::error::JsError as CoreJsError;
use sourcemap::SourceMap;
use std::collections::HashMap;
use std::str;
@ -18,13 +21,13 @@ pub trait SourceMapGetter {
/// find a SourceMap.
pub type CachedMaps = HashMap<String, Option<SourceMap>>;
/// Apply a source map to a deno_core::JsError, returning a JsError where file
/// names and line/column numbers point to the location in the original source,
/// rather than the transpiled source code.
/// Apply a source map to a `deno_core::JsError`, returning a `JsError` where
/// file names and line/column numbers point to the location in the original
/// source, rather than the transpiled source code.
pub fn apply_source_map<G: SourceMapGetter>(
js_error: &deno_core::JsError,
js_error: &CoreJsError,
getter: &G,
) -> deno_core::JsError {
) -> CoreJsError {
// Note that js_error.frames has already been source mapped in
// prepareStackTrace().
let mut mappings_map: CachedMaps = HashMap::new();
@ -67,7 +70,7 @@ pub fn apply_source_map<G: SourceMapGetter>(
_ => js_error.source_line.clone(),
};
deno_core::JsError {
CoreJsError {
message: js_error.message.clone(),
source_line,
script_resource_name,
@ -194,7 +197,7 @@ mod tests {
#[test]
fn apply_source_map_line() {
let e = deno_core::JsError {
let e = CoreJsError {
message: "TypeError: baz".to_string(),
source_line: Some("foo".to_string()),
script_resource_name: Some("foo_bar.ts".to_string()),

View file

@ -9,7 +9,7 @@ use crate::metrics::Metrics;
use crate::permissions::Permissions;
use crate::tsc::TargetLib;
use crate::web_worker::WebWorkerHandle;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use deno_core::ModuleLoadId;
use deno_core::ModuleLoader;
use deno_core::ModuleSpecifier;
@ -77,7 +77,7 @@ impl ModuleLoader for State {
specifier: &str,
referrer: &str,
is_main: bool,
) -> Result<ModuleSpecifier, ErrBox> {
) -> Result<ModuleSpecifier, AnyError> {
if !is_main {
if let Some(import_map) = &self.import_map {
let result = import_map.resolve(specifier, referrer)?;
@ -127,7 +127,7 @@ impl ModuleLoader for State {
module_specifier: &ModuleSpecifier,
maybe_referrer: Option<String>,
is_dyn_import: bool,
) -> Pin<Box<dyn Future<Output = Result<(), ErrBox>>>> {
) -> Pin<Box<dyn Future<Output = Result<(), AnyError>>>> {
let module_specifier = module_specifier.clone();
let target_lib = self.target_lib.clone();
let maybe_import_map = self.import_map.clone();
@ -174,7 +174,7 @@ impl State {
main_module: ModuleSpecifier,
maybe_import_map: Option<ImportMap>,
is_internal: bool,
) -> Result<Rc<Self>, ErrBox> {
) -> Result<Rc<Self>, AnyError> {
let fl = &global_state.flags;
let state = State {
global_state: global_state.clone(),
@ -202,7 +202,7 @@ impl State {
global_state: &Arc<GlobalState>,
shared_permissions: Option<Permissions>,
main_module: ModuleSpecifier,
) -> Result<Rc<Self>, ErrBox> {
) -> Result<Rc<Self>, AnyError> {
let fl = &global_state.flags;
let state = State {
global_state: global_state.clone(),
@ -226,7 +226,7 @@ impl State {
}
#[inline]
pub fn check_read(&self, path: &Path) -> Result<(), ErrBox> {
pub fn check_read(&self, path: &Path) -> Result<(), AnyError> {
self.permissions.borrow().check_read(path)
}
@ -237,49 +237,49 @@ impl State {
&self,
path: &Path,
display: &str,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
self.permissions.borrow().check_read_blind(path, display)
}
#[inline]
pub fn check_write(&self, path: &Path) -> Result<(), ErrBox> {
pub fn check_write(&self, path: &Path) -> Result<(), AnyError> {
self.permissions.borrow().check_write(path)
}
#[inline]
pub fn check_env(&self) -> Result<(), ErrBox> {
pub fn check_env(&self) -> Result<(), AnyError> {
self.permissions.borrow().check_env()
}
#[inline]
pub fn check_net(&self, hostname: &str, port: u16) -> Result<(), ErrBox> {
pub fn check_net(&self, hostname: &str, port: u16) -> Result<(), AnyError> {
self.permissions.borrow().check_net(hostname, port)
}
#[inline]
pub fn check_net_url(&self, url: &url::Url) -> Result<(), ErrBox> {
pub fn check_net_url(&self, url: &url::Url) -> Result<(), AnyError> {
self.permissions.borrow().check_net_url(url)
}
#[inline]
pub fn check_run(&self) -> Result<(), ErrBox> {
pub fn check_run(&self) -> Result<(), AnyError> {
self.permissions.borrow().check_run()
}
#[inline]
pub fn check_hrtime(&self) -> Result<(), ErrBox> {
pub fn check_hrtime(&self) -> Result<(), AnyError> {
self.permissions.borrow().check_hrtime()
}
#[inline]
pub fn check_plugin(&self, filename: &Path) -> Result<(), ErrBox> {
pub fn check_plugin(&self, filename: &Path) -> Result<(), AnyError> {
self.permissions.borrow().check_plugin(filename)
}
pub fn check_dyn_import(
&self,
module_specifier: &ModuleSpecifier,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let u = module_specifier.as_url();
// TODO(bartlomieju): temporary fix to prevent hitting `unreachable`
// statement that is actually reachable...

View file

@ -2,7 +2,7 @@
use crate::fs as deno_fs;
use crate::installer::is_remote_url;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use std::path::Path;
use std::path::PathBuf;
use url::Url;
@ -34,7 +34,7 @@ fn is_supported(p: &Path) -> bool {
pub fn prepare_test_modules_urls(
include: Vec<String>,
root_path: &PathBuf,
) -> Result<Vec<Url>, ErrBox> {
) -> Result<Vec<Url>, AnyError> {
let (include_paths, include_urls): (Vec<String>, Vec<String>) =
include.into_iter().partition(|n| !is_remote_url(n));

View file

@ -24,7 +24,8 @@ use crate::tsc_config;
use crate::version;
use crate::worker::Worker;
use core::task::Context;
use deno_core::ErrBox;
use deno_core::error::generic_error;
use deno_core::error::AnyError;
use deno_core::ModuleSpecifier;
use futures::future::Future;
use futures::future::FutureExt;
@ -166,7 +167,7 @@ impl DerefMut for CompilerWorker {
}
impl Future for CompilerWorker {
type Output = Result<(), ErrBox>;
type Output = Result<(), AnyError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let inner = self.get_mut();
@ -252,7 +253,7 @@ pub struct CompilerConfig {
impl CompilerConfig {
/// Take the passed flag and resolve the file name relative to the cwd.
pub fn load(maybe_config_path: Option<String>) -> Result<Self, ErrBox> {
pub fn load(maybe_config_path: Option<String>) -> Result<Self, AnyError> {
if maybe_config_path.is_none() {
return Ok(Self {
path: Some(PathBuf::new()),
@ -439,7 +440,7 @@ impl TsCompiler {
file_fetcher: SourceFileFetcher,
flags: Flags,
disk_cache: DiskCache,
) -> Result<Self, ErrBox> {
) -> Result<Self, AnyError> {
let config = CompilerConfig::load(flags.config_path.clone())?;
let use_disk_cache = !flags.reload;
@ -495,7 +496,7 @@ impl TsCompiler {
&self,
url: &Url,
build_info: &Option<String>,
) -> Result<bool, ErrBox> {
) -> Result<bool, AnyError> {
if let Some(build_info_str) = build_info.as_ref() {
let build_inf_json: Value = serde_json::from_str(build_info_str)?;
let program_val = build_inf_json["program"].as_object().unwrap();
@ -557,7 +558,7 @@ impl TsCompiler {
permissions: Permissions,
module_graph: &ModuleGraph,
allow_js: bool,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let module_url = source_file.url.clone();
let build_info_key = self
.disk_cache
@ -646,7 +647,7 @@ impl TsCompiler {
let compile_response: CompileResponse = serde_json::from_str(&json_str)?;
if !compile_response.diagnostics.0.is_empty() {
return Err(ErrBox::error(compile_response.diagnostics.to_string()));
return Err(generic_error(compile_response.diagnostics.to_string()));
}
maybe_log_stats(compile_response.stats);
@ -664,7 +665,7 @@ impl TsCompiler {
&self,
global_state: &Arc<GlobalState>,
module_specifier: ModuleSpecifier,
) -> Result<String, ErrBox> {
) -> Result<String, AnyError> {
debug!(
"Invoking the compiler to bundle. module_name: {}",
module_specifier.to_string()
@ -768,7 +769,7 @@ impl TsCompiler {
maybe_log_stats(bundle_response.stats);
if !bundle_response.diagnostics.0.is_empty() {
return Err(ErrBox::error(bundle_response.diagnostics.to_string()));
return Err(generic_error(bundle_response.diagnostics.to_string()));
}
assert!(bundle_response.bundle_output.is_some());
@ -779,7 +780,7 @@ impl TsCompiler {
pub async fn transpile(
&self,
module_graph: &ModuleGraph,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let mut source_files: Vec<TranspileSourceFile> = Vec::new();
for (_, value) in module_graph.iter() {
let url = Url::parse(&value.url).expect("Filename is not a valid url");
@ -919,7 +920,7 @@ impl TsCompiler {
pub fn get_compiled_module(
&self,
module_url: &Url,
) -> Result<CompiledModule, ErrBox> {
) -> Result<CompiledModule, AnyError> {
let compiled_source_file = self.get_compiled_source_file(module_url)?;
let compiled_module = CompiledModule {
@ -936,7 +937,7 @@ impl TsCompiler {
pub fn get_compiled_source_file(
&self,
module_url: &Url,
) -> Result<SourceFile, ErrBox> {
) -> Result<SourceFile, AnyError> {
let cache_key = self
.disk_cache
.get_cache_filename_with_extension(&module_url, "js");
@ -993,7 +994,7 @@ impl TsCompiler {
pub fn get_source_map_file(
&self,
module_specifier: &ModuleSpecifier,
) -> Result<SourceFile, ErrBox> {
) -> Result<SourceFile, AnyError> {
let cache_key = self
.disk_cache
.get_cache_filename_with_extension(module_specifier.as_url(), "js.map");
@ -1133,7 +1134,7 @@ async fn execute_in_same_thread(
global_state: &Arc<GlobalState>,
permissions: Permissions,
req: String,
) -> Result<String, ErrBox> {
) -> Result<String, AnyError> {
let mut worker = create_compiler_worker(&global_state, permissions);
let script = format!("globalThis.tsCompilerOnMessage({{ data: {} }});", req);
worker.execute2("<compiler>", &script)?;
@ -1147,7 +1148,7 @@ async fn create_runtime_module_graph(
root_name: &str,
sources: &Option<HashMap<String, String>>,
type_files: Vec<String>,
) -> Result<(Vec<String>, ModuleGraph), ErrBox> {
) -> Result<(Vec<String>, ModuleGraph), AnyError> {
let mut root_names = vec![];
let mut module_graph_loader = ModuleGraphLoader::new(
global_state.file_fetcher.clone(),
@ -1181,13 +1182,11 @@ async fn create_runtime_module_graph(
Ok((root_names, module_graph_loader.get_graph()))
}
/// Because TS compiler can raise runtime error, we need to
/// manually convert formatted JsError into and ErrBox.
fn js_error_to_errbox(error: ErrBox) -> ErrBox {
fn js_error_to_errbox(error: AnyError) -> AnyError {
match error.downcast::<JsError>() {
Ok(js_error) => {
let msg = format!("Error in TS compiler:\n{}", js_error);
ErrBox::error(msg)
generic_error(msg)
}
Err(error) => error,
}
@ -1200,7 +1199,7 @@ pub async fn runtime_compile(
root_name: &str,
sources: &Option<HashMap<String, String>>,
maybe_options: &Option<String>,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let mut user_options = if let Some(options) = maybe_options {
tsc_config::parse_raw_config(options)?
} else {
@ -1302,7 +1301,7 @@ pub async fn runtime_bundle(
root_name: &str,
sources: &Option<HashMap<String, String>>,
maybe_options: &Option<String>,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let mut user_options = if let Some(options) = maybe_options {
tsc_config::parse_raw_config(options)?
} else {
@ -1404,7 +1403,7 @@ pub async fn runtime_transpile(
permissions: Permissions,
sources: &HashMap<String, String>,
maybe_options: &Option<String>,
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let user_options = if let Some(options) = maybe_options {
tsc_config::parse_raw_config(options)?
} else {
@ -1466,7 +1465,7 @@ pub fn pre_process_file(
media_type: MediaType,
source_code: &str,
analyze_dynamic_imports: bool,
) -> Result<(Vec<ImportDesc>, Vec<TsReferenceDesc>), ErrBox> {
) -> Result<(Vec<ImportDesc>, Vec<TsReferenceDesc>), AnyError> {
let specifier = ModuleSpecifier::resolve_url_or_path(file_name)?;
let module = parse(&specifier, source_code, &media_type)?;

View file

@ -1,6 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use deno_core::ErrBox;
use deno_core::error::AnyError;
use jsonc_parser::JsonValue;
use serde::Deserialize;
use serde_json::Value;
@ -139,7 +139,7 @@ struct TSConfigJson {
type_acquisition: Option<Value>,
}
pub fn parse_raw_config(config_text: &str) -> Result<Value, ErrBox> {
pub fn parse_raw_config(config_text: &str) -> Result<Value, AnyError> {
assert!(!config_text.is_empty());
let jsonc = jsonc_parser::parse_to_value(config_text)?.unwrap();
Ok(jsonc_to_serde(jsonc))
@ -149,7 +149,7 @@ pub fn parse_raw_config(config_text: &str) -> Result<Value, ErrBox> {
/// The result also contains any options that were ignored.
pub fn parse_config(
config_text: &str,
) -> Result<(Value, Option<IgnoredCompilerOptions>), ErrBox> {
) -> Result<(Value, Option<IgnoredCompilerOptions>), AnyError> {
assert!(!config_text.is_empty());
let jsonc = jsonc_parser::parse_to_value(config_text)?.unwrap();
let config: TSConfigJson = serde_json::from_value(jsonc_to_serde(jsonc))?;

View file

@ -10,7 +10,9 @@ extern crate semver_parser;
use crate::futures::FutureExt;
use crate::http_util::fetch_once;
use crate::http_util::FetchOnceResult;
use crate::ErrBox;
use crate::AnyError;
use deno_core::error::custom_error;
use regex::Regex;
use reqwest::{redirect::Policy, Client};
use semver_parser::version::parse as semver_parse;
@ -35,7 +37,7 @@ const ARCHIVE_NAME: &str = "deno-x86_64-apple-darwin.zip";
#[cfg(target_os = "linux")]
const ARCHIVE_NAME: &str = "deno-x86_64-unknown-linux-gnu.zip";
async fn get_latest_version(client: &Client) -> Result<Version, ErrBox> {
async fn get_latest_version(client: &Client) -> Result<Version, AnyError> {
println!("Checking for latest version");
let body = client
.get(Url::parse(
@ -57,7 +59,7 @@ pub async fn upgrade_command(
version: Option<String>,
output: Option<PathBuf>,
ca_file: Option<String>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let mut client_builder = Client::builder().redirect(Policy::none());
// If we have been provided a CA Certificate, add it into the HTTP client
@ -132,7 +134,7 @@ fn download_package(
url: &Url,
client: Client,
version: &Version,
) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, ErrBox>>>> {
) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, AnyError>>>> {
println!("downloading {}", url);
let url = url.clone();
let version = version.clone();
@ -160,21 +162,21 @@ fn download_package(
fut.boxed_local()
}
fn compose_url_to_exec(version: &Version) -> Result<Url, ErrBox> {
fn compose_url_to_exec(version: &Version) -> Result<Url, AnyError> {
let s = format!(
"https://github.com/denoland/deno/releases/download/v{}/{}",
version, ARCHIVE_NAME
);
Url::parse(&s).map_err(ErrBox::from)
Url::parse(&s).map_err(AnyError::from)
}
fn find_version(text: &str) -> Result<String, ErrBox> {
fn find_version(text: &str) -> Result<String, AnyError> {
let re = Regex::new(r#"v([^\?]+)?""#)?;
if let Some(_mat) = re.find(text) {
let mat = _mat.as_str();
return Ok(mat[1..mat.len() - 1].to_string());
}
Err(ErrBox::new("NotFound", "Cannot read latest tag version"))
Err(custom_error("NotFound", "Cannot read latest tag version"))
}
fn unpack(archive_data: Vec<u8>) -> Result<PathBuf, std::io::Error> {
@ -260,7 +262,7 @@ fn replace_exe(new: &Path, old: &Path) -> Result<(), std::io::Error> {
fn check_exe(
exe_path: &Path,
expected_version: &Version,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let output = Command::new(exe_path)
.arg("-V")
.stderr(std::process::Stdio::inherit())

View file

@ -6,8 +6,8 @@ use crate::state::State;
use crate::worker::Worker;
use crate::worker::WorkerEvent;
use crate::worker::WorkerHandle;
use deno_core::error::AnyError;
use deno_core::v8;
use deno_core::ErrBox;
use futures::channel::mpsc;
use futures::future::FutureExt;
use futures::stream::StreamExt;
@ -164,7 +164,7 @@ impl DerefMut for WebWorker {
}
impl Future for WebWorker {
type Output = Result<(), ErrBox>;
type Output = Result<(), AnyError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let inner = self.get_mut();

View file

@ -7,7 +7,7 @@ use crate::js;
use crate::ops;
use crate::ops::io::get_stdio;
use crate::state::State;
use deno_core::ErrBox;
use deno_core::error::AnyError;
use deno_core::JsRuntime;
use deno_core::ModuleId;
use deno_core::ModuleSpecifier;
@ -33,8 +33,8 @@ use url::Url;
/// worker.
pub enum WorkerEvent {
Message(Box<[u8]>),
Error(ErrBox),
TerminalError(ErrBox),
Error(AnyError),
TerminalError(AnyError),
}
pub struct WorkerChannelsInternal {
@ -50,7 +50,7 @@ pub struct WorkerHandle {
impl WorkerHandle {
/// Post message to worker as a host.
pub fn post_message(&self, buf: Box<[u8]>) -> Result<(), ErrBox> {
pub fn post_message(&self, buf: Box<[u8]>) -> Result<(), AnyError> {
let mut sender = self.sender.clone();
sender.try_send(buf)?;
Ok(())
@ -58,7 +58,7 @@ impl WorkerHandle {
/// Get the event with lock.
/// Return error if more than one listener tries to get event
pub async fn get_event(&self) -> Result<Option<WorkerEvent>, ErrBox> {
pub async fn get_event(&self) -> Result<Option<WorkerEvent>, AnyError> {
let mut receiver = self.receiver.try_lock()?;
Ok(receiver.next().await)
}
@ -149,7 +149,7 @@ impl Worker {
}
/// Same as execute2() but the filename defaults to "$CWD/__anonymous__".
pub fn execute(&mut self, js_source: &str) -> Result<(), ErrBox> {
pub fn execute(&mut self, js_source: &str) -> Result<(), AnyError> {
let path = env::current_dir().unwrap().join("__anonymous__");
let url = Url::from_file_path(path).unwrap();
self.execute2(url.as_str(), js_source)
@ -161,7 +161,7 @@ impl Worker {
&mut self,
js_filename: &str,
js_source: &str,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
self.isolate.execute(js_filename, js_source)
}
@ -169,7 +169,7 @@ impl Worker {
pub async fn preload_module(
&mut self,
module_specifier: &ModuleSpecifier,
) -> Result<ModuleId, ErrBox> {
) -> Result<ModuleId, AnyError> {
self.isolate.load_module(module_specifier, None).await
}
@ -177,7 +177,7 @@ impl Worker {
pub async fn execute_module(
&mut self,
module_specifier: &ModuleSpecifier,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let id = self.preload_module(module_specifier).await?;
self.wait_for_inspector_session();
self.isolate.mod_evaluate(id)
@ -189,7 +189,7 @@ impl Worker {
&mut self,
module_specifier: &ModuleSpecifier,
code: String,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let id = self
.isolate
.load_module(module_specifier, Some(code))
@ -226,7 +226,7 @@ impl Drop for Worker {
}
impl Future for Worker {
type Output = Result<(), ErrBox>;
type Output = Result<(), AnyError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let inner = self.get_mut();
@ -297,7 +297,7 @@ impl MainWorker {
pub fn create(
global_state: &Arc<GlobalState>,
main_module: ModuleSpecifier,
) -> Result<MainWorker, ErrBox> {
) -> Result<MainWorker, AnyError> {
let state = State::new(
&global_state,
None,

View file

@ -13,8 +13,10 @@ repository = "https://github.com/denoland/deno"
path = "lib.rs"
[dependencies]
anyhow = "1.0.32"
downcast-rs = "1.2.0"
futures = "0.3.5"
indexmap = "1.6.0"
lazy_static = "1.4.0"
libc = "0.2.77"
log = "0.4.11"
@ -22,7 +24,6 @@ rusty_v8 = "0.10.0"
serde_json = { version = "1.0.57", features = ["preserve_order"] }
smallvec = "1.4.2"
url = "2.1.1"
indexmap = "1.6.0"
[[example]]
name = "http_bench_bin_ops"

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use crate::ErrBox;
use crate::JsError;
use crate::error::AnyError;
use crate::error::JsError;
use crate::JsRuntime;
use crate::JsRuntimeState;
use crate::Op;
@ -396,8 +396,8 @@ fn send<'s>(
let state = state_rc.borrow_mut();
let op_id = match v8::Local::<v8::Integer>::try_from(args.get(0))
.map_err(ErrBox::from)
.and_then(|l| OpId::try_from(l.value()).map_err(ErrBox::from))
.map_err(AnyError::from)
.and_then(|l| OpId::try_from(l.value()).map_err(AnyError::from))
{
Ok(op_id) => op_id,
Err(err) => {

View file

@ -1,113 +1,88 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use rusty_v8 as v8;
use std::any::Any;
use std::any::TypeId;
use std::borrow::Cow;
use std::convert::TryFrom;
use std::convert::TryInto;
use std::error::Error;
use std::fmt;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::io;
// The Send and Sync traits are required because deno is multithreaded and we
// need to be able to handle errors across threads.
pub trait AnyError: Any + Error + Send + Sync + 'static {}
impl<T> AnyError for T where T: Any + Error + Send + Sync + Sized + 'static {}
/// A generic wrapper that can encapsulate any concrete error type.
pub type AnyError = anyhow::Error;
/// Creates a new error with a caller-specified error class name and message.
pub fn custom_error(
class: &'static str,
message: impl Into<Cow<'static, str>>,
) -> AnyError {
CustomError {
class,
message: message.into(),
}
.into()
}
pub fn generic_error(message: impl Into<Cow<'static, str>>) -> AnyError {
custom_error("Error", message)
}
pub fn type_error(message: impl Into<Cow<'static, str>>) -> AnyError {
custom_error("TypeError", message)
}
pub fn uri_error(message: impl Into<Cow<'static, str>>) -> AnyError {
custom_error("URIError", message)
}
pub fn last_os_error() -> AnyError {
io::Error::last_os_error().into()
}
pub fn bad_resource(message: impl Into<Cow<'static, str>>) -> AnyError {
custom_error("BadResource", message)
}
pub fn bad_resource_id() -> AnyError {
custom_error("BadResource", "Bad resource ID")
}
pub fn not_supported() -> AnyError {
custom_error("NotSupported", "The operation is supported")
}
pub fn resource_unavailable() -> AnyError {
custom_error(
"Busy",
"Resource is unavailable because it is in use by a promise",
)
}
/// A simple error type that lets the creator specify both the error message and
/// the error class name. This type is private; externally it only ever appears
/// wrapped in an `AnyError`. To retrieve the error class name from a wrapped
/// `CustomError`, use the function `get_custom_error_class()`.
#[derive(Debug)]
pub enum ErrBox {
Simple {
class: &'static str,
message: Cow<'static, str>,
},
Boxed(Box<dyn AnyError>),
struct CustomError {
class: &'static str,
message: Cow<'static, str>,
}
impl ErrBox {
pub fn new(
class: &'static str,
message: impl Into<Cow<'static, str>>,
) -> Self {
Self::Simple {
class,
message: message.into(),
}
}
pub fn bad_resource(message: impl Into<Cow<'static, str>>) -> Self {
Self::new("BadResource", message)
}
pub fn bad_resource_id() -> Self {
Self::new("BadResource", "Bad resource ID")
}
pub fn error(message: impl Into<Cow<'static, str>>) -> Self {
Self::new("Error", message)
}
pub fn not_supported() -> Self {
Self::new("NotSupported", "The operation is supported")
}
pub fn resource_unavailable() -> Self {
Self::new(
"Busy",
"Resource is unavailable because it is in use by a promise",
)
}
pub fn type_error(message: impl Into<Cow<'static, str>>) -> Self {
Self::new("TypeError", message)
}
pub fn last_os_error() -> Self {
Self::from(io::Error::last_os_error())
}
pub fn downcast<T: AnyError>(self) -> Result<T, Self> {
match self {
Self::Boxed(error) if Any::type_id(&*error) == TypeId::of::<T>() => {
let error = Box::into_raw(error) as *mut T;
let error = unsafe { Box::from_raw(error) };
Ok(*error)
}
other => Err(other),
}
}
pub fn downcast_ref<T: AnyError>(&self) -> Option<&T> {
match self {
Self::Boxed(error) if Any::type_id(&**error) == TypeId::of::<T>() => {
let error = &**error as *const dyn AnyError as *const T;
let error = unsafe { &*error };
Some(error)
}
_ => None,
}
impl Display for CustomError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str(&self.message)
}
}
impl fmt::Display for ErrBox {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Simple { message, .. } => f.write_str(message),
Self::Boxed(error) => error.fmt(f),
}
}
}
impl Error for CustomError {}
impl<T: AnyError> From<T> for ErrBox {
fn from(error: T) -> Self {
Self::Boxed(Box::new(error))
}
}
impl From<Box<dyn AnyError>> for ErrBox {
fn from(boxed: Box<dyn AnyError>) -> Self {
Self::Boxed(boxed)
}
/// If this error was crated with `custom_error()`, return the specified error
/// class name. In all other cases this function returns `None`.
pub fn get_custom_error_class(error: &AnyError) -> Option<&'static str> {
error.downcast_ref::<CustomError>().map(|e| e.class)
}
/// A `JsError` represents an exception coming from V8, with stack frames and
@ -153,7 +128,7 @@ fn get_property<'a>(
}
impl JsError {
pub(crate) fn create(js_error: Self) -> ErrBox {
pub(crate) fn create(js_error: Self) -> AnyError {
js_error.into()
}
@ -355,8 +330,8 @@ fn format_source_loc(
format!("{}:{}:{}", file_name, line_number, column_number)
}
impl fmt::Display for JsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
impl Display for JsError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if let Some(script_resource_name) = &self.script_resource_name {
if self.line_number.is_some() && self.start_column.is_some() {
assert!(self.line_number.is_some());
@ -397,9 +372,9 @@ impl fmt::Display for JsError {
pub(crate) fn attach_handle_to_error(
scope: &mut v8::Isolate,
err: ErrBox,
err: AnyError,
handle: v8::Local<v8::Value>,
) -> ErrBox {
) -> AnyError {
// TODO(bartomieju): this is a special case...
ErrWithV8Handle::new(scope, err, handle).into()
}
@ -407,14 +382,14 @@ pub(crate) fn attach_handle_to_error(
// TODO(piscisaureus): rusty_v8 should implement the Error trait on
// values of type v8::Global<T>.
pub struct ErrWithV8Handle {
err: ErrBox,
err: AnyError,
handle: v8::Global<v8::Value>,
}
impl ErrWithV8Handle {
pub fn new(
scope: &mut v8::Isolate,
err: ErrBox,
err: AnyError,
handle: v8::Local<v8::Value>,
) -> Self {
let handle = v8::Global::new(scope, handle);
@ -434,15 +409,15 @@ unsafe impl Sync for ErrWithV8Handle {}
impl Error for ErrWithV8Handle {}
impl fmt::Display for ErrWithV8Handle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.err.fmt(f)
impl Display for ErrWithV8Handle {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
<AnyError as Display>::fmt(&self.err, f)
}
}
impl fmt::Debug for ErrWithV8Handle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.err.fmt(f)
impl Debug for ErrWithV8Handle {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
<Self as Display>::fmt(self, f)
}
}
@ -452,15 +427,13 @@ mod tests {
#[test]
fn test_bad_resource() {
let err = ErrBox::bad_resource("Resource has been closed");
assert!(matches!(err, ErrBox::Simple { class: "BadResource", .. }));
let err = bad_resource("Resource has been closed");
assert_eq!(err.to_string(), "Resource has been closed");
}
#[test]
fn test_bad_resource_id() {
let err = ErrBox::bad_resource_id();
assert!(matches!(err, ErrBox::Simple { class: "BadResource", .. }));
let err = bad_resource_id();
assert_eq!(err.to_string(), "Bad resource ID");
}
}

View file

@ -1,9 +1,10 @@
#[macro_use]
extern crate log;
use deno_core::error::bad_resource_id;
use deno_core::error::AnyError;
use deno_core::js_check;
use deno_core::BufVec;
use deno_core::ErrBox;
use deno_core::JsRuntime;
use deno_core::OpState;
use deno_core::ZeroCopyBuf;
@ -53,7 +54,7 @@ fn op_listen(
state: &mut OpState,
_args: Value,
_bufs: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
debug!("listen");
let addr = "127.0.0.1:4544".parse::<SocketAddr>().unwrap();
let std_listener = std::net::TcpListener::bind(&addr)?;
@ -66,7 +67,7 @@ fn op_close(
state: &mut OpState,
args: Value,
_buf: &mut [ZeroCopyBuf],
) -> Result<Value, ErrBox> {
) -> Result<Value, AnyError> {
let rid: u32 = args
.get("rid")
.unwrap()
@ -79,14 +80,14 @@ fn op_close(
.resource_table
.close(rid)
.map(|_| serde_json::json!(()))
.ok_or_else(ErrBox::bad_resource_id)
.ok_or_else(bad_resource_id)
}
fn op_accept(
state: Rc<RefCell<OpState>>,
args: Value,
_bufs: BufVec,
) -> impl Future<Output = Result<Value, ErrBox>> {
) -> impl Future<Output = Result<Value, AnyError>> {
let rid: u32 = args
.get("rid")
.unwrap()
@ -101,7 +102,7 @@ fn op_accept(
let listener = resource_table
.get_mut::<TcpListener>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
listener.poll_accept(cx)?.map(|(stream, _addr)| {
let rid = resource_table.add("tcpStream", Box::new(stream));
Ok(serde_json::json!({ "rid": rid }))
@ -113,7 +114,7 @@ fn op_read(
state: Rc<RefCell<OpState>>,
args: Value,
mut bufs: BufVec,
) -> impl Future<Output = Result<Value, ErrBox>> {
) -> impl Future<Output = Result<Value, AnyError>> {
assert_eq!(bufs.len(), 1, "Invalid number of arguments");
let rid: u32 = args
@ -125,12 +126,12 @@ fn op_read(
.unwrap();
debug!("read rid={}", rid);
poll_fn(move |cx| -> Poll<Result<Value, ErrBox>> {
poll_fn(move |cx| -> Poll<Result<Value, AnyError>> {
let resource_table = &mut state.borrow_mut().resource_table;
let stream = resource_table
.get_mut::<TcpStream>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
Pin::new(stream)
.poll_read(cx, &mut bufs[0])?
.map(|nread| Ok(serde_json::json!({ "nread": nread })))
@ -141,7 +142,7 @@ fn op_write(
state: Rc<RefCell<OpState>>,
args: Value,
bufs: BufVec,
) -> impl Future<Output = Result<Value, ErrBox>> {
) -> impl Future<Output = Result<Value, AnyError>> {
assert_eq!(bufs.len(), 1, "Invalid number of arguments");
let rid: u32 = args
@ -158,7 +159,7 @@ fn op_write(
let stream = resource_table
.get_mut::<TcpStream>(rid)
.ok_or_else(ErrBox::bad_resource_id)?;
.ok_or_else(bad_resource_id)?;
Pin::new(stream)
.poll_write(cx, &bufs[0])?
.map(|nwritten| Ok(serde_json::json!({ "nwritten": nwritten })))

View file

@ -9,7 +9,7 @@ extern crate lazy_static;
extern crate log;
mod bindings;
mod errors;
pub mod error;
mod flags;
mod gotham_state;
mod module_specifier;
@ -24,9 +24,6 @@ mod zero_copy_buf;
pub use rusty_v8 as v8;
pub use crate::errors::AnyError;
pub use crate::errors::ErrBox;
pub use crate::errors::JsError;
pub use crate::flags::v8_set_flags;
pub use crate::module_specifier::ModuleResolutionError;
pub use crate::module_specifier::ModuleSpecifier;

View file

@ -2,8 +2,9 @@
use rusty_v8 as v8;
use crate::error::generic_error;
use crate::error::AnyError;
use crate::module_specifier::ModuleSpecifier;
use crate::ErrBox;
use futures::future::FutureExt;
use futures::stream::FuturesUnordered;
use futures::stream::Stream;
@ -48,8 +49,9 @@ pub struct ModuleSource {
}
pub type PrepareLoadFuture =
dyn Future<Output = (ModuleLoadId, Result<RecursiveModuleLoad, ErrBox>)>;
pub type ModuleSourceFuture = dyn Future<Output = Result<ModuleSource, ErrBox>>;
dyn Future<Output = (ModuleLoadId, Result<RecursiveModuleLoad, AnyError>)>;
pub type ModuleSourceFuture =
dyn Future<Output = Result<ModuleSource, AnyError>>;
pub trait ModuleLoader {
/// Returns an absolute URL.
@ -64,7 +66,7 @@ pub trait ModuleLoader {
specifier: &str,
referrer: &str,
_is_main: bool,
) -> Result<ModuleSpecifier, ErrBox>;
) -> Result<ModuleSpecifier, AnyError>;
/// Given ModuleSpecifier, load its source code.
///
@ -91,7 +93,7 @@ pub trait ModuleLoader {
_module_specifier: &ModuleSpecifier,
_maybe_referrer: Option<String>,
_is_dyn_import: bool,
) -> Pin<Box<dyn Future<Output = Result<(), ErrBox>>>> {
) -> Pin<Box<dyn Future<Output = Result<(), AnyError>>>> {
async { Ok(()) }.boxed_local()
}
}
@ -106,8 +108,8 @@ impl ModuleLoader for NoopModuleLoader {
_specifier: &str,
_referrer: &str,
_is_main: bool,
) -> Result<ModuleSpecifier, ErrBox> {
Err(ErrBox::error("Module loading is not supported"))
) -> Result<ModuleSpecifier, AnyError> {
Err(generic_error("Module loading is not supported"))
}
fn load(
@ -116,7 +118,7 @@ impl ModuleLoader for NoopModuleLoader {
_maybe_referrer: Option<ModuleSpecifier>,
_is_dyn_import: bool,
) -> Pin<Box<ModuleSourceFuture>> {
async { Err(ErrBox::error("Module loading is not supported")) }
async { Err(generic_error("Module loading is not supported")) }
.boxed_local()
}
}
@ -188,7 +190,7 @@ impl RecursiveModuleLoad {
}
}
pub async fn prepare(self) -> (ModuleLoadId, Result<Self, ErrBox>) {
pub async fn prepare(self) -> (ModuleLoadId, Result<Self, AnyError>) {
let (module_specifier, maybe_referrer) = match self.state {
LoadState::ResolveMain(ref specifier, _) => {
let spec = match self.loader.resolve(specifier, ".", true) {
@ -223,7 +225,7 @@ impl RecursiveModuleLoad {
}
}
fn add_root(&mut self) -> Result<(), ErrBox> {
fn add_root(&mut self) -> Result<(), AnyError> {
let module_specifier = match self.state {
LoadState::ResolveMain(ref specifier, _) => {
self.loader.resolve(specifier, ".", true)?
@ -273,7 +275,7 @@ impl RecursiveModuleLoad {
}
impl Stream for RecursiveModuleLoad {
type Item = Result<ModuleSource, ErrBox>;
type Item = Result<ModuleSource, AnyError>;
fn poll_next(
self: Pin<&mut Self>,
@ -518,7 +520,7 @@ mod tests {
}
impl Future for DelayedSourceCodeFuture {
type Output = Result<ModuleSource, ErrBox>;
type Output = Result<ModuleSource, AnyError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let inner = self.get_mut();
@ -549,7 +551,7 @@ mod tests {
specifier: &str,
referrer: &str,
_is_root: bool,
) -> Result<ModuleSpecifier, ErrBox> {
) -> Result<ModuleSpecifier, AnyError> {
let referrer = if referrer == "." {
"file:///"
} else {

View file

@ -1,8 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use crate::error::type_error;
use crate::error::AnyError;
use crate::gotham_state::GothamState;
use crate::BufVec;
use crate::ErrBox;
use crate::ZeroCopyBuf;
use futures::Future;
use indexmap::IndexMap;
@ -150,12 +151,12 @@ fn op_table() {
pub fn json_op_sync<F>(op_fn: F) -> Box<OpFn>
where
F: Fn(&mut OpState, Value, &mut [ZeroCopyBuf]) -> Result<Value, ErrBox>
F: Fn(&mut OpState, Value, &mut [ZeroCopyBuf]) -> Result<Value, AnyError>
+ 'static,
{
Box::new(move |state: Rc<RefCell<OpState>>, mut bufs: BufVec| -> Op {
let result = serde_json::from_slice(&bufs[0])
.map_err(crate::ErrBox::from)
.map_err(AnyError::from)
.and_then(|args| op_fn(&mut state.borrow_mut(), args, &mut bufs[1..]));
let buf =
json_serialize_op_result(None, result, state.borrow().get_error_class_fn);
@ -166,15 +167,15 @@ where
pub fn json_op_async<F, R>(op_fn: F) -> Box<OpFn>
where
F: Fn(Rc<RefCell<OpState>>, Value, BufVec) -> R + 'static,
R: Future<Output = Result<Value, ErrBox>> + 'static,
R: Future<Output = Result<Value, AnyError>> + 'static,
{
let try_dispatch_op =
move |state: Rc<RefCell<OpState>>, bufs: BufVec| -> Result<Op, ErrBox> {
move |state: Rc<RefCell<OpState>>, bufs: BufVec| -> Result<Op, AnyError> {
let args: Value = serde_json::from_slice(&bufs[0])?;
let promise_id = args
.get("promiseId")
.and_then(Value::as_u64)
.ok_or_else(|| ErrBox::type_error("missing or invalid `promiseId`"))?;
.ok_or_else(|| type_error("missing or invalid `promiseId`"))?;
let bufs = bufs[1..].into();
use crate::futures::FutureExt;
let fut = op_fn(state.clone(), args, bufs).map(move |result| {
@ -201,7 +202,7 @@ where
fn json_serialize_op_result(
promise_id: Option<u64>,
result: Result<serde_json::Value, crate::ErrBox>,
result: Result<serde_json::Value, AnyError>,
get_error_class_fn: crate::runtime::GetErrorClassFn,
) -> Box<[u8]> {
let value = match result {

View file

@ -3,8 +3,10 @@
use rusty_v8 as v8;
use crate::bindings;
use crate::errors::attach_handle_to_error;
use crate::errors::ErrWithV8Handle;
use crate::error::attach_handle_to_error;
use crate::error::AnyError;
use crate::error::ErrWithV8Handle;
use crate::error::JsError;
use crate::futures::FutureExt;
use crate::module_specifier::ModuleSpecifier;
use crate::modules::LoadState;
@ -20,8 +22,6 @@ use crate::ops::*;
use crate::shared_queue::SharedQueue;
use crate::shared_queue::RECOMMENDED_SIZE;
use crate::BufVec;
use crate::ErrBox;
use crate::JsError;
use crate::OpState;
use futures::stream::FuturesUnordered;
use futures::stream::StreamExt;
@ -52,9 +52,10 @@ pub enum Snapshot {
Boxed(Box<[u8]>),
}
type JsErrorCreateFn = dyn Fn(JsError) -> ErrBox;
type JsErrorCreateFn = dyn Fn(JsError) -> AnyError;
pub type GetErrorClassFn = &'static dyn for<'e> Fn(&'e ErrBox) -> &'static str;
pub type GetErrorClassFn =
&'static dyn for<'e> Fn(&'e AnyError) -> &'static str;
/// Objects that need to live as long as the isolate
#[derive(Default)]
@ -329,14 +330,15 @@ impl JsRuntime {
/// Executes traditional JavaScript code (traditional = not ES modules)
///
/// ErrBox can be downcast to a type that exposes additional information about
/// the V8 exception. By default this type is JsError, however it may be a
/// different type if JsRuntime::set_js_error_create_fn() has been used.
/// `AnyError` can be downcast to a type that exposes additional information
/// about the V8 exception. By default this type is `JsError`, however it may
/// be a different type if `JsRuntime::set_js_error_create_fn()` has been
/// used.
pub fn execute(
&mut self,
js_filename: &str,
js_source: &str,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
self.shared_init();
let state_rc = Self::state(self);
@ -376,9 +378,10 @@ impl JsRuntime {
/// Takes a snapshot. The isolate should have been created with will_snapshot
/// set to true.
///
/// ErrBox can be downcast to a type that exposes additional information about
/// the V8 exception. By default this type is JsError, however it may be a
/// different type if JsRuntime::set_js_error_create_fn() has been used.
/// `AnyError` can be downcast to a type that exposes additional information
/// about the V8 exception. By default this type is `JsError`, however it may
/// be a different type if `JsRuntime::set_js_error_create_fn()` has been
/// used.
pub fn snapshot(&mut self) -> v8::StartupData {
assert!(self.snapshot_creator.is_some());
let state = Self::state(self);
@ -466,7 +469,7 @@ where
}
impl Future for JsRuntime {
type Output = Result<(), ErrBox>;
type Output = Result<(), AnyError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let runtime = self.get_mut();
@ -590,7 +593,7 @@ impl JsRuntimeState {
/// is set to JsError::create.
pub fn set_js_error_create_fn(
&mut self,
f: impl Fn(JsError) -> ErrBox + 'static,
f: impl Fn(JsError) -> AnyError + 'static,
) {
self.js_error_create_fn = Box::new(f);
}
@ -633,7 +636,7 @@ impl JsRuntimeState {
fn async_op_response<'s>(
scope: &mut v8::HandleScope<'s>,
maybe_buf: Option<(OpId, Box<[u8]>)>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let context = scope.get_current_context();
let global: v8::Local<v8::Value> = context.global(scope).into();
let js_recv_cb = JsRuntime::state(scope)
@ -662,7 +665,9 @@ fn async_op_response<'s>(
}
}
fn drain_macrotasks<'s>(scope: &mut v8::HandleScope<'s>) -> Result<(), ErrBox> {
fn drain_macrotasks<'s>(
scope: &mut v8::HandleScope<'s>,
) -> Result<(), AnyError> {
let context = scope.get_current_context();
let global: v8::Local<v8::Value> = context.global(scope).into();
@ -699,7 +704,7 @@ fn drain_macrotasks<'s>(scope: &mut v8::HandleScope<'s>) -> Result<(), ErrBox> {
pub(crate) fn exception_to_err_result<'s, T>(
scope: &mut v8::HandleScope<'s>,
exception: v8::Local<v8::Value>,
) -> Result<T, ErrBox> {
) -> Result<T, AnyError> {
// TODO(piscisaureus): in rusty_v8, `is_execution_terminating()` should
// also be implemented on `struct Isolate`.
let is_terminating_exception =
@ -738,7 +743,7 @@ pub(crate) fn exception_to_err_result<'s, T>(
fn check_promise_exceptions<'s>(
scope: &mut v8::HandleScope<'s>,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let state_rc = JsRuntime::state(scope);
let mut state = state_rc.borrow_mut();
@ -752,7 +757,7 @@ fn check_promise_exceptions<'s>(
}
}
pub fn js_check<T>(r: Result<T, ErrBox>) -> T {
pub fn js_check<T>(r: Result<T, AnyError>) -> T {
if let Err(e) = r {
panic!(e.to_string());
}
@ -782,7 +787,7 @@ impl JsRuntime {
main: bool,
name: &str,
source: &str,
) -> Result<ModuleId, ErrBox> {
) -> Result<ModuleId, AnyError> {
let state_rc = Self::state(self);
let scope = &mut v8::HandleScope::with_context(
&mut **self,
@ -831,10 +836,11 @@ impl JsRuntime {
/// Instantiates a ES module
///
/// ErrBox can be downcast to a type that exposes additional information about
/// the V8 exception. By default this type is JsError, however it may be a
/// different type if JsRuntime::set_js_error_create_fn() has been used.
fn mod_instantiate(&mut self, id: ModuleId) -> Result<(), ErrBox> {
/// `AnyError` can be downcast to a type that exposes additional information
/// about the V8 exception. By default this type is `JsError`, however it may
/// be a different type if `JsRuntime::set_js_error_create_fn()` has been
/// used.
fn mod_instantiate(&mut self, id: ModuleId) -> Result<(), AnyError> {
let state_rc = Self::state(self);
let state = state_rc.borrow();
let scope = &mut v8::HandleScope::with_context(
@ -867,10 +873,11 @@ impl JsRuntime {
/// Evaluates an already instantiated ES module.
///
/// ErrBox can be downcast to a type that exposes additional information about
/// the V8 exception. By default this type is JsError, however it may be a
/// different type if JsRuntime::set_js_error_create_fn() has been used.
pub fn mod_evaluate(&mut self, id: ModuleId) -> Result<(), ErrBox> {
/// `AnyError` can be downcast to a type that exposes additional information
/// about the V8 exception. By default this type is `JsError`, however it may
/// be a different type if `JsRuntime::set_js_error_create_fn()` has been
/// used.
pub fn mod_evaluate(&mut self, id: ModuleId) -> Result<(), AnyError> {
self.shared_init();
let state_rc = Self::state(self);
@ -939,8 +946,8 @@ impl JsRuntime {
fn dyn_import_error(
&mut self,
id: ModuleLoadId,
err: ErrBox,
) -> Result<(), ErrBox> {
err: AnyError,
) -> Result<(), AnyError> {
let state_rc = Self::state(self);
let scope = &mut v8::HandleScope::with_context(
@ -973,7 +980,7 @@ impl JsRuntime {
&mut self,
id: ModuleLoadId,
mod_id: ModuleId,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let state_rc = Self::state(self);
debug!("dyn_import_done {} {:?}", id, mod_id);
@ -1010,7 +1017,7 @@ impl JsRuntime {
fn prepare_dyn_imports(
&mut self,
cx: &mut Context,
) -> Poll<Result<(), ErrBox>> {
) -> Poll<Result<(), AnyError>> {
let state_rc = Self::state(self);
loop {
@ -1041,7 +1048,10 @@ impl JsRuntime {
}
}
fn poll_dyn_imports(&mut self, cx: &mut Context) -> Poll<Result<(), ErrBox>> {
fn poll_dyn_imports(
&mut self,
cx: &mut Context,
) -> Poll<Result<(), AnyError>> {
let state_rc = Self::state(self);
loop {
let poll_result = {
@ -1100,7 +1110,7 @@ impl JsRuntime {
&mut self,
info: ModuleSource,
load: &mut RecursiveModuleLoad,
) -> Result<(), ErrBox> {
) -> Result<(), AnyError> {
let ModuleSource {
code,
module_url_specified,
@ -1189,7 +1199,7 @@ impl JsRuntime {
&mut self,
specifier: &ModuleSpecifier,
code: Option<String>,
) -> Result<ModuleId, ErrBox> {
) -> Result<ModuleId, AnyError> {
self.shared_init();
let loader = {
let state_rc = Self::state(self);
@ -1870,7 +1880,7 @@ pub mod tests {
specifier: &str,
referrer: &str,
_is_main: bool,
) -> Result<ModuleSpecifier, ErrBox> {
) -> Result<ModuleSpecifier, AnyError> {
self.count.fetch_add(1, Ordering::Relaxed);
assert_eq!(specifier, "./b.js");
assert_eq!(referrer, "file:///a.js");
@ -1979,7 +1989,7 @@ pub mod tests {
specifier: &str,
referrer: &str,
_is_main: bool,
) -> Result<ModuleSpecifier, ErrBox> {
) -> Result<ModuleSpecifier, AnyError> {
self.count.fetch_add(1, Ordering::Relaxed);
assert_eq!(specifier, "/foo.js");
assert_eq!(referrer, "file:///dyn_import2.js");
@ -2038,7 +2048,7 @@ pub mod tests {
specifier: &str,
referrer: &str,
_is_main: bool,
) -> Result<ModuleSpecifier, ErrBox> {
) -> Result<ModuleSpecifier, AnyError> {
let c = self.resolve_count.fetch_add(1, Ordering::Relaxed);
assert!(c < 4);
assert_eq!(specifier, "./b.js");
@ -2068,7 +2078,7 @@ pub mod tests {
_module_specifier: &ModuleSpecifier,
_maybe_referrer: Option<String>,
_is_dyn_import: bool,
) -> Pin<Box<dyn Future<Output = Result<(), ErrBox>>>> {
) -> Pin<Box<dyn Future<Output = Result<(), AnyError>>>> {
self.prepare_load_count.fetch_add(1, Ordering::Relaxed);
async { Ok(()) }.boxed_local()
}
@ -2160,7 +2170,7 @@ pub mod tests {
specifier: &str,
referrer: &str,
_is_main: bool,
) -> Result<ModuleSpecifier, ErrBox> {
) -> Result<ModuleSpecifier, AnyError> {
assert_eq!(specifier, "file:///main.js");
assert_eq!(referrer, ".");
let s = ModuleSpecifier::resolve_import(specifier, referrer).unwrap();