From dd8a10948195f231a6a9eb652e3f208813904ad6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Fri, 21 Feb 2020 10:36:13 -0500 Subject: [PATCH] refactor: remove unneeded ErrorKinds (#3936) --- cli/deno_error.rs | 208 ++++++----------- cli/file_fetcher.rs | 2 +- cli/js/buffer.ts | 12 +- cli/js/buffer_test.ts | 6 +- cli/js/chmod_test.ts | 10 +- cli/js/chown_test.ts | 17 +- cli/js/copy_file_test.ts | 18 +- cli/js/deno.ts | 2 +- cli/js/dir_test.ts | 4 +- cli/js/dispatch_json.ts | 4 +- cli/js/dispatch_json_test.ts | 2 - cli/js/dispatch_minimal.ts | 6 +- cli/js/dispatch_minimal_test.ts | 2 - cli/js/errors.ts | 217 +++++++++++++++--- cli/js/event_target.ts | 19 +- cli/js/fetch_test.ts | 8 +- cli/js/files_test.ts | 11 +- cli/js/lib.deno.ns.d.ts | 111 +++++---- cli/js/link_test.ts | 10 +- cli/js/make_temp_test.ts | 16 +- cli/js/mkdir_test.ts | 5 +- cli/js/net_test.ts | 14 +- cli/js/os.ts | 4 +- cli/js/os_test.ts | 10 +- cli/js/permissions_test.ts | 12 +- cli/js/process_test.ts | 23 +- cli/js/read_dir_test.ts | 10 +- cli/js/read_file_test.ts | 8 +- cli/js/read_link_test.ts | 8 +- cli/js/realpath_test.ts | 12 +- cli/js/remove_test.ts | 74 +++--- cli/js/rename_test.ts | 8 +- cli/js/stat_test.ts | 24 +- cli/js/streams/pipe-to.ts | 4 +- cli/js/symlink_test.ts | 4 +- cli/js/text_encoding.ts | 9 +- cli/js/text_encoding_test.ts | 2 +- cli/js/tls_test.ts | 18 +- cli/js/truncate_test.ts | 6 +- cli/js/utime_test.ts | 14 +- cli/js/write_file_test.ts | 18 +- cli/msg.rs | 36 --- cli/ops/dispatch_minimal.rs | 4 +- cli/ops/files.rs | 2 +- cli/ops/worker_host.rs | 29 +-- cli/tests/044_bad_resource.ts.out | 5 +- cli/tests/error_004_missing_module.ts.out | 5 +- .../error_005_missing_dynamic_import.ts.out | 5 +- cli/tests/error_006_import_ext_failure.ts.out | 5 +- .../error_011_bad_module_specifier.ts.out | 6 +- ...or_012_bad_dynamic_import_specifier.ts.out | 6 +- cli/tests/error_type_definitions.ts.out | 6 +- std/encoding/yaml/error.ts | 6 +- std/fs/copy.ts | 4 +- std/fs/empty_dir.ts | 14 +- std/fs/ensure_dir.ts | 6 +- std/fs/ensure_file.ts | 6 +- std/fs/ensure_link_test.ts | 6 +- std/fs/exists.ts | 14 +- std/fs/expand_glob.ts | 6 +- std/fs/walk_test.ts | 9 +- std/http/file_server.ts | 4 +- std/node/module.ts | 2 +- std/node/process_test.ts | 4 +- std/path/glob.ts | 7 +- std/testing/runner.ts | 4 +- 66 files changed, 553 insertions(+), 620 deletions(-) diff --git a/cli/deno_error.rs b/cli/deno_error.rs index 0e1a8d9cf3..97c7c8a7c5 100644 --- a/cli/deno_error.rs +++ b/cli/deno_error.rs @@ -1,8 +1,34 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use crate::diagnostics::Diagnostic; -use crate::fmt_errors::JSError; + +//! This module implements error serialization; it +//! allows to serialize Rust errors to be sent to JS runtime. +//! +//! Currently it is deeply intertwined with `ErrBox` which is +//! not optimal since not every ErrBox can be "JS runtime error"; +//! eg. there's no way to throw JSError/Diagnostic from within JS runtime +//! +//! There are many types of errors in Deno: +//! - ErrBox: a generic boxed object. This is the super type of all +//! errors handled in Rust. +//! - JSError: exceptions thrown from V8 into Rust. Usually a user exception. +//! These are basically a big JSON structure which holds information about +//! line numbers. We use this to pretty-print stack traces. These are +//! never passed back into the runtime. +//! - DenoError: these are errors that happen during ops, which are passed +//! back into the runtime, where an exception object is created and thrown. +//! DenoErrors have an integer code associated with them - access this via the kind() method. +//! - 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 exceptions. +//! +//! TODO: +//! - rename DenoError to OpError? +//! - rename JSError to RuntimeException. merge V8Exception? +//! - rename ErrorKind::Other. This corresponds to a generic exception thrown as the +//! global `Error` in JS: +//! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error + use crate::import_map::ImportMapError; -pub use crate::msg::ErrorKind; use deno_core::AnyError; use deno_core::ErrBox; use deno_core::ModuleResolutionError; @@ -16,6 +42,34 @@ use std::fmt; use std::io; use url; +// Warning! The values in this enum are duplicated in js/errors.ts +// Update carefully! +#[allow(non_camel_case_types)] +#[repr(i8)] +#[derive(Clone, Copy, PartialEq, Debug)] +pub enum ErrorKind { + NotFound = 1, + PermissionDenied = 2, + ConnectionRefused = 3, + ConnectionReset = 4, + ConnectionAborted = 5, + NotConnected = 6, + AddrInUse = 7, + AddrNotAvailable = 8, + BrokenPipe = 9, + AlreadyExists = 10, + InvalidData = 13, + TimedOut = 14, + Interrupted = 15, + WriteZero = 16, + UnexpectedEof = 17, + BadResource = 18, + Http = 19, + URIError = 20, + TypeError = 21, + Other = 22, +} + #[derive(Debug)] pub struct DenoError { kind: ErrorKind, @@ -76,11 +130,11 @@ pub fn permission_denied_msg(msg: String) -> ErrBox { } pub fn no_buffer_specified() -> ErrBox { - StaticError(ErrorKind::InvalidInput, "no buffer specified").into() + StaticError(ErrorKind::TypeError, "no buffer specified").into() } pub fn invalid_address_syntax() -> ErrBox { - StaticError(ErrorKind::InvalidInput, "invalid address syntax").into() + StaticError(ErrorKind::TypeError, "invalid address syntax").into() } pub fn other_error(msg: String) -> ErrBox { @@ -103,18 +157,6 @@ impl GetErrorKind for StaticError { } } -impl GetErrorKind for JSError { - fn kind(&self) -> ErrorKind { - ErrorKind::JSError - } -} - -impl GetErrorKind for Diagnostic { - fn kind(&self) -> ErrorKind { - ErrorKind::Diagnostic - } -} - impl GetErrorKind for ImportMapError { fn kind(&self) -> ErrorKind { ErrorKind::Other @@ -123,12 +165,7 @@ impl GetErrorKind for ImportMapError { impl GetErrorKind for ModuleResolutionError { fn kind(&self) -> ErrorKind { - use ModuleResolutionError::*; - match self { - InvalidUrl(ref err) | InvalidBaseUrl(ref err) => err.kind(), - InvalidPath(_) => ErrorKind::InvalidPath, - ImportPrefixMissing(_, _) => ErrorKind::ImportPrefixMissing, - } + ErrorKind::URIError } } @@ -156,13 +193,13 @@ impl GetErrorKind for io::Error { AddrNotAvailable => ErrorKind::AddrNotAvailable, BrokenPipe => ErrorKind::BrokenPipe, AlreadyExists => ErrorKind::AlreadyExists, - WouldBlock => ErrorKind::WouldBlock, - InvalidInput => ErrorKind::InvalidInput, + InvalidInput => ErrorKind::TypeError, InvalidData => ErrorKind::InvalidData, TimedOut => ErrorKind::TimedOut, Interrupted => ErrorKind::Interrupted, WriteZero => ErrorKind::WriteZero, UnexpectedEof => ErrorKind::UnexpectedEof, + WouldBlock => unreachable!(), _ => ErrorKind::Other, } } @@ -170,7 +207,7 @@ impl GetErrorKind for io::Error { impl GetErrorKind for url::ParseError { fn kind(&self) -> ErrorKind { - ErrorKind::UrlParse + ErrorKind::URIError } } @@ -211,8 +248,8 @@ impl GetErrorKind for serde_json::error::Error { fn kind(&self) -> ErrorKind { use serde_json::error::*; match self.classify() { - Category::Io => ErrorKind::InvalidInput, - Category::Syntax => ErrorKind::InvalidInput, + Category::Io => ErrorKind::TypeError, + Category::Syntax => ErrorKind::TypeError, Category::Data => ErrorKind::InvalidData, Category::Eof => ErrorKind::UnexpectedEof, } @@ -230,10 +267,13 @@ mod unix { fn kind(&self) -> ErrorKind { match self { Sys(EPERM) => ErrorKind::PermissionDenied, - Sys(EINVAL) => ErrorKind::InvalidInput, + Sys(EINVAL) => ErrorKind::TypeError, Sys(ENOENT) => ErrorKind::NotFound, - Sys(_) => ErrorKind::UnixError, - _ => ErrorKind::Other, + Sys(UnknownErrno) => unreachable!(), + Sys(_) => unreachable!(), + Error::InvalidPath => ErrorKind::TypeError, + Error::InvalidUtf8 => ErrorKind::InvalidData, + Error::UnsupportedOperation => unreachable!(), } } } @@ -268,11 +308,9 @@ impl GetErrorKind for dyn AnyError { None .or_else(|| self.downcast_ref::().map(Get::kind)) - .or_else(|| self.downcast_ref::().map(Get::kind)) .or_else(|| self.downcast_ref::().map(Get::kind)) .or_else(|| self.downcast_ref::().map(Get::kind)) .or_else(|| self.downcast_ref::().map(Get::kind)) - .or_else(|| self.downcast_ref::().map(Get::kind)) .or_else(|| self.downcast_ref::().map(Get::kind)) .or_else(|| self.downcast_ref::().map(Get::kind)) .or_else(|| self.downcast_ref::().map(Get::kind)) @@ -294,93 +332,7 @@ impl GetErrorKind for dyn AnyError { #[cfg(test)] mod tests { use super::*; - use crate::colors::strip_ansi_codes; - use crate::diagnostics::Diagnostic; - use crate::diagnostics::DiagnosticCategory; - use crate::diagnostics::DiagnosticItem; use deno_core::ErrBox; - use deno_core::StackFrame; - use deno_core::V8Exception; - - fn js_error() -> JSError { - JSError::new(V8Exception { - message: "Error: foo bar".to_string(), - source_line: None, - script_resource_name: None, - line_number: None, - start_position: None, - end_position: None, - error_level: None, - start_column: None, - end_column: None, - frames: vec![ - StackFrame { - line: 4, - column: 16, - script_name: "foo_bar.ts".to_string(), - function_name: "foo".to_string(), - is_eval: false, - is_constructor: false, - is_wasm: false, - }, - StackFrame { - line: 5, - column: 20, - script_name: "bar_baz.ts".to_string(), - function_name: "qat".to_string(), - is_eval: false, - is_constructor: false, - is_wasm: false, - }, - StackFrame { - line: 1, - column: 1, - script_name: "deno_main.js".to_string(), - function_name: "".to_string(), - is_eval: false, - is_constructor: false, - is_wasm: false, - }, - ], - }) - } - - fn diagnostic() -> Diagnostic { - Diagnostic { - items: vec![ - DiagnosticItem { - message: "Example 1".to_string(), - message_chain: None, - code: 2322, - category: DiagnosticCategory::Error, - start_position: Some(267), - end_position: Some(273), - source_line: Some(" values: o => [".to_string()), - line_number: Some(18), - script_resource_name: Some( - "deno/tests/complex_diagnostics.ts".to_string(), - ), - start_column: Some(2), - end_column: Some(8), - related_information: None, - }, - DiagnosticItem { - message: "Example 2".to_string(), - message_chain: None, - code: 2000, - category: DiagnosticCategory::Error, - start_position: Some(2), - end_position: Some(2), - source_line: Some(" values: undefined,".to_string()), - line_number: Some(128), - script_resource_name: Some("/foo/bar.ts".to_string()), - start_column: Some(2), - end_column: Some(8), - related_information: None, - }, - ], - } - } fn io_error() -> io::Error { io::Error::from(io::ErrorKind::NotFound) @@ -414,26 +366,12 @@ mod tests { #[test] fn test_url_error() { let err = ErrBox::from(url_error()); - assert_eq!(err.kind(), ErrorKind::UrlParse); + assert_eq!(err.kind(), ErrorKind::URIError); assert_eq!(err.to_string(), "empty host"); } // TODO find a way to easily test tokio errors and unix errors - #[test] - fn test_diagnostic() { - let err = ErrBox::from(diagnostic()); - assert_eq!(err.kind(), ErrorKind::Diagnostic); - assert_eq!(strip_ansi_codes(&err.to_string()), "error TS2322: Example 1\n\n► deno/tests/complex_diagnostics.ts:19:3\n\n19 values: o => [\n ~~~~~~\n\nerror TS2000: Example 2\n\n► /foo/bar.ts:129:3\n\n129 values: undefined,\n ~~~~~~\n\n\nFound 2 errors.\n"); - } - - #[test] - fn test_js_error() { - let err = ErrBox::from(js_error()); - assert_eq!(err.kind(), ErrorKind::JSError); - assert_eq!(strip_ansi_codes(&err.to_string()), "error: Error: foo bar\n at foo (foo_bar.ts:5:17)\n at qat (bar_baz.ts:6:21)\n at deno_main.js:2:2"); - } - #[test] fn test_import_map_error() { let err = ErrBox::from(import_map_error()); @@ -466,7 +404,7 @@ mod tests { #[test] fn test_no_buffer_specified() { let err = no_buffer_specified(); - assert_eq!(err.kind(), ErrorKind::InvalidInput); + assert_eq!(err.kind(), ErrorKind::TypeError); assert_eq!(err.to_string(), "no buffer specified"); } } diff --git a/cli/file_fetcher.rs b/cli/file_fetcher.rs index ea82f151ed..a529c20efd 100644 --- a/cli/file_fetcher.rs +++ b/cli/file_fetcher.rs @@ -251,7 +251,7 @@ impl SourceFileFetcher { fn fetch_local_file(&self, module_url: &Url) -> Result { let filepath = module_url.to_file_path().map_err(|()| { ErrBox::from(DenoError::new( - ErrorKind::InvalidPath, + ErrorKind::URIError, "File URL contains invalid path".to_owned(), )) })?; diff --git a/cli/js/buffer.ts b/cli/js/buffer.ts index 2dec9fac6a..dab5a4bfc9 100644 --- a/cli/js/buffer.ts +++ b/cli/js/buffer.ts @@ -7,7 +7,6 @@ import { Reader, Writer, EOF, SyncReader, SyncWriter } from "./io.ts"; import { assert } from "./util.ts"; import { TextDecoder } from "./text_encoding.ts"; -import { DenoError, ErrorKind } from "./errors.ts"; // MIN_READ is the minimum ArrayBuffer size passed to a read call by // buffer.ReadFrom. As long as the Buffer has at least MIN_READ bytes beyond @@ -162,7 +161,7 @@ export class Buffer implements Reader, SyncReader, Writer, SyncWriter { /** _grow() grows the buffer to guarantee space for n more bytes. * It returns the index where bytes should be written. - * If the buffer can't grow it will throw with ErrTooLarge. + * If the buffer can't grow it will throw with Error. */ private _grow(n: number): number { const m = this.length; @@ -183,10 +182,7 @@ export class Buffer implements Reader, SyncReader, Writer, SyncWriter { // don't spend all our time copying. copyBytes(this.buf, this.buf.subarray(this.off)); } else if (c > MAX_SIZE - c - n) { - throw new DenoError( - ErrorKind.TooLarge, - "The buffer cannot be grown beyond the maximum size." - ); + throw new Error("The buffer cannot be grown beyond the maximum size."); } else { // Not enough space anywhere, we need to allocate. const buf = new Uint8Array(2 * c + n); @@ -202,7 +198,7 @@ export class Buffer implements Reader, SyncReader, Writer, SyncWriter { /** grow() grows the buffer's capacity, if necessary, to guarantee space for * another n bytes. After grow(n), at least n bytes can be written to the * buffer without another allocation. If n is negative, grow() will panic. If - * the buffer can't grow it will throw ErrTooLarge. + * the buffer can't grow it will throw Error. * Based on https://golang.org/pkg/bytes/#Buffer.Grow */ grow(n: number): void { @@ -215,7 +211,7 @@ export class Buffer implements Reader, SyncReader, Writer, SyncWriter { /** readFrom() reads data from r until EOF and appends it to the buffer, * growing the buffer as needed. It returns the number of bytes read. If the - * buffer becomes too large, readFrom will panic with ErrTooLarge. + * buffer becomes too large, readFrom will panic with Error. * Based on https://golang.org/pkg/bytes/#Buffer.ReadFrom */ async readFrom(r: Reader): Promise { diff --git a/cli/js/buffer_test.ts b/cli/js/buffer_test.ts index 72c0cab4b8..769b46521e 100644 --- a/cli/js/buffer_test.ts +++ b/cli/js/buffer_test.ts @@ -3,7 +3,7 @@ // This code has been ported almost directly from Go's src/bytes/buffer_test.go // Copyright 2009 The Go Authors. All rights reserved. BSD license. // https://github.com/golang/go/blob/master/LICENSE -import { assert, assertEquals, test } from "./test_util.ts"; +import { assertEquals, assert, assertStrContains, test } from "./test_util.ts"; const { Buffer, readAll, readAllSync, writeAll, writeAllSync } = Deno; type Buffer = Deno.Buffer; @@ -159,8 +159,8 @@ test(async function bufferTooLargeByteWrites(): Promise { err = e; } - assertEquals(err.kind, Deno.ErrorKind.TooLarge); - assertEquals(err.name, "TooLarge"); + assert(err instanceof Error); + assertStrContains(err.message, "grown beyond the maximum size"); }); test(async function bufferLargeByteReads(): Promise { diff --git a/cli/js/chmod_test.ts b/cli/js/chmod_test.ts index b3b0a2ae2a..24c69db7ab 100644 --- a/cli/js/chmod_test.ts +++ b/cli/js/chmod_test.ts @@ -60,8 +60,7 @@ testPerm({ write: true }, function chmodSyncFailure(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm({ write: false }, function chmodSyncPerm(): void { @@ -71,7 +70,7 @@ testPerm({ write: false }, function chmodSyncPerm(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -134,8 +133,7 @@ testPerm({ write: true }, async function chmodFailure(): Promise { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm({ write: false }, async function chmodPerm(): Promise { @@ -145,6 +143,6 @@ testPerm({ write: false }, async function chmodPerm(): Promise { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); diff --git a/cli/js/chown_test.ts b/cli/js/chown_test.ts index 61132ae313..a1c12860d4 100644 --- a/cli/js/chown_test.ts +++ b/cli/js/chown_test.ts @@ -1,5 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { testPerm, assertEquals } from "./test_util.ts"; +import { testPerm, assertEquals, assert } from "./test_util.ts"; // chown on Windows is noop for now, so ignore its testing on Windows if (Deno.build.os !== "win") { @@ -31,8 +31,7 @@ if (Deno.build.os !== "win") { try { await Deno.chown(filePath, 1000, 1000); } catch (e) { - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } }); @@ -45,8 +44,7 @@ if (Deno.build.os !== "win") { try { Deno.chownSync(filePath, uid, gid); } catch (e) { - assertEquals(e.kind, Deno.ErrorKind.NotFound); - assertEquals(e.name, "NotFound"); + assert(e instanceof Deno.Err.NotFound); } } ); @@ -60,8 +58,7 @@ if (Deno.build.os !== "win") { try { await Deno.chown(filePath, uid, gid); } catch (e) { - assertEquals(e.kind, Deno.ErrorKind.NotFound); - assertEquals(e.name, "NotFound"); + assert(e instanceof Deno.Err.NotFound); } } ); @@ -77,8 +74,7 @@ if (Deno.build.os !== "win") { // try changing the file's owner to root Deno.chownSync(filePath, 0, 0); } catch (e) { - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } Deno.removeSync(dirPath, { recursive: true }); }); @@ -96,8 +92,7 @@ if (Deno.build.os !== "win") { // try changing the file's owner to root await Deno.chown(filePath, 0, 0); } catch (e) { - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } await Deno.remove(dirPath, { recursive: true }); }); diff --git a/cli/js/copy_file_test.ts b/cli/js/copy_file_test.ts index 88dc3fdbf0..567b246b7b 100644 --- a/cli/js/copy_file_test.ts +++ b/cli/js/copy_file_test.ts @@ -43,8 +43,7 @@ testPerm({ write: true, read: true }, function copyFileSyncFailure(): void { err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm({ write: true, read: false }, function copyFileSyncPerm1(): void { @@ -53,8 +52,7 @@ testPerm({ write: true, read: false }, function copyFileSyncPerm1(): void { Deno.copyFileSync("/from.txt", "/to.txt"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -65,8 +63,7 @@ testPerm({ write: false, read: true }, function copyFileSyncPerm2(): void { Deno.copyFileSync("/from.txt", "/to.txt"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -113,8 +110,7 @@ testPerm({ read: true, write: true }, async function copyFileFailure(): Promise< err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm( @@ -142,8 +138,7 @@ testPerm({ read: false, write: true }, async function copyFilePerm1(): Promise< await Deno.copyFile("/from.txt", "/to.txt"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -156,8 +151,7 @@ testPerm({ read: true, write: false }, async function copyFilePerm2(): Promise< await Deno.copyFile("/from.txt", "/to.txt"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); diff --git a/cli/js/deno.ts b/cli/js/deno.ts index cdfedcd76b..8ccca90961 100644 --- a/cli/js/deno.ts +++ b/cli/js/deno.ts @@ -22,7 +22,7 @@ export { } from "./diagnostics.ts"; export { chdir, cwd } from "./dir.ts"; export { applySourceMap } from "./error_stack.ts"; -export { ErrorKind, DenoError } from "./errors.ts"; +export { Err } from "./errors.ts"; export { FileInfo } from "./file_info.ts"; export { File, diff --git a/cli/js/dir_test.ts b/cli/js/dir_test.ts index 4b03eaedd8..f936986aa2 100644 --- a/cli/js/dir_test.ts +++ b/cli/js/dir_test.ts @@ -29,7 +29,7 @@ testPerm({ write: true }, function dirCwdError(): void { Deno.cwd(); throw Error("current directory removed, should throw error"); } catch (err) { - if (err instanceof Deno.DenoError) { + if (err instanceof Deno.Err.NotFound) { console.log(err.name === "NotFound"); } else { throw Error("raised different exception"); @@ -45,7 +45,7 @@ testPerm({ write: true }, function dirChdirError(): void { Deno.chdir(path); throw Error("directory not available, should throw error"); } catch (err) { - if (err instanceof Deno.DenoError) { + if (err instanceof Deno.Err.NotFound) { console.log(err.name === "NotFound"); } else { throw Error("raised different exception"); diff --git a/cli/js/dispatch_json.ts b/cli/js/dispatch_json.ts index adccb69c6e..b0859e1ba3 100644 --- a/cli/js/dispatch_json.ts +++ b/cli/js/dispatch_json.ts @@ -2,7 +2,7 @@ import * as util from "./util.ts"; import { TextEncoder, TextDecoder } from "./text_encoding.ts"; import { core } from "./core.ts"; -import { ErrorKind, DenoError } from "./errors.ts"; +import { ErrorKind, constructError } from "./errors.ts"; // eslint-disable-next-line @typescript-eslint/no-explicit-any type Ok = any; @@ -37,7 +37,7 @@ function encode(args: object): Uint8Array { function unwrapResponse(res: JsonResponse): Ok { if (res.err != null) { - throw new DenoError(res.err!.kind, res.err!.message); + return constructError(res.err!.kind, res.err!.message); } util.assert(res.ok != null); return res.ok; diff --git a/cli/js/dispatch_json_test.ts b/cli/js/dispatch_json_test.ts index c3fd6945b3..90f93746ef 100644 --- a/cli/js/dispatch_json_test.ts +++ b/cli/js/dispatch_json_test.ts @@ -2,7 +2,6 @@ import { test, testPerm, assert, - assertEquals, assertMatch, unreachable } from "./test_util.ts"; @@ -31,5 +30,4 @@ test(async function malformedJsonControlBuffer(): Promise { const resJson = JSON.parse(resText) as any; assert(!resJson.ok); assert(resJson.err); - assertEquals(resJson.err!.kind, Deno.ErrorKind.InvalidInput); }); diff --git a/cli/js/dispatch_minimal.ts b/cli/js/dispatch_minimal.ts index 1ce3fbaef7..203701085c 100644 --- a/cli/js/dispatch_minimal.ts +++ b/cli/js/dispatch_minimal.ts @@ -2,7 +2,7 @@ import * as util from "./util.ts"; import { core } from "./core.ts"; import { TextDecoder } from "./text_encoding.ts"; -import { ErrorKind, DenoError } from "./errors.ts"; +import { Err, ErrorKind, constructError } from "./errors.ts"; const promiseTableMin = new Map>(); // Note it's important that promiseId starts at 1 instead of 0, because sync @@ -43,7 +43,7 @@ export function recordFromBufMinimal(ui8: Uint8Array): RecordMinimal { const message = decoder.decode(ui8.slice(12)); err = { kind, message }; } else if (ui8.length != 12) { - err = { kind: ErrorKind.InvalidData, message: "Bad message" }; + throw new Err.InvalidData("BadMessage"); } return { @@ -56,7 +56,7 @@ export function recordFromBufMinimal(ui8: Uint8Array): RecordMinimal { function unwrapResponse(res: RecordMinimal): number { if (res.err != null) { - throw new DenoError(res.err!.kind, res.err!.message); + return constructError(res.err!.kind, res.err!.message); } return res.result; } diff --git a/cli/js/dispatch_minimal_test.ts b/cli/js/dispatch_minimal_test.ts index 12c70d375b..75381204f9 100644 --- a/cli/js/dispatch_minimal_test.ts +++ b/cli/js/dispatch_minimal_test.ts @@ -36,9 +36,7 @@ test(async function malformedMinimalControlBuffer(): Promise { header.byteLength / 4 ); const arg = buf32[1]; - const result = buf32[2]; const message = new TextDecoder().decode(res.slice(12)).trim(); assert(arg < 0); - assertEquals(result, Deno.ErrorKind.InvalidInput); assertEquals(message, "Unparsable control buffer"); }); diff --git a/cli/js/errors.ts b/cli/js/errors.ts index 0f75453cea..0844b0a569 100644 --- a/cli/js/errors.ts +++ b/cli/js/errors.ts @@ -1,27 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -/** A Deno specific error. The `kind` property is set to a specific error code - * which can be used to in application logic. - * - * try { - * somethingThatMightThrow(); - * } catch (e) { - * if ( - * e instanceof Deno.DenoError && - * e.kind === Deno.ErrorKind.NotFound - * ) { - * console.error("NotFound error!"); - * } - * } - * - */ -export class DenoError extends Error { - constructor(readonly kind: T, msg: string) { - super(msg); - this.name = ErrorKind[kind]; - } -} - // Warning! The values in this enum are duplicated in cli/msg.rs // Update carefully! export enum ErrorKind { @@ -35,22 +13,189 @@ export enum ErrorKind { AddrNotAvailable = 8, BrokenPipe = 9, AlreadyExists = 10, - WouldBlock = 11, - InvalidInput = 12, InvalidData = 13, TimedOut = 14, Interrupted = 15, WriteZero = 16, - Other = 17, - UnexpectedEof = 18, - BadResource = 19, - UrlParse = 20, - Http = 21, - TooLarge = 22, - InvalidSeekMode = 23, - UnixError = 24, - InvalidPath = 25, - ImportPrefixMissing = 26, - Diagnostic = 27, - JSError = 28 + UnexpectedEof = 17, + BadResource = 18, + Http = 19, + URIError = 20, + TypeError = 21, + Other = 22 } + +export function constructError(kind: ErrorKind, msg: string): never { + switch (kind) { + case ErrorKind.TypeError: + throw new TypeError(msg); + case ErrorKind.Other: + throw new Error(msg); + case ErrorKind.URIError: + throw new URIError(msg); + case ErrorKind.NotFound: + throw new NotFound(msg); + case ErrorKind.PermissionDenied: + throw new PermissionDenied(msg); + case ErrorKind.ConnectionRefused: + throw new ConnectionRefused(msg); + case ErrorKind.ConnectionReset: + throw new ConnectionReset(msg); + case ErrorKind.ConnectionAborted: + throw new ConnectionAborted(msg); + case ErrorKind.NotConnected: + throw new NotConnected(msg); + case ErrorKind.AddrInUse: + throw new AddrInUse(msg); + case ErrorKind.AddrNotAvailable: + throw new AddrNotAvailable(msg); + case ErrorKind.BrokenPipe: + throw new BrokenPipe(msg); + case ErrorKind.AlreadyExists: + throw new AlreadyExists(msg); + case ErrorKind.InvalidData: + throw new InvalidData(msg); + case ErrorKind.TimedOut: + throw new TimedOut(msg); + case ErrorKind.Interrupted: + throw new Interrupted(msg); + case ErrorKind.WriteZero: + throw new WriteZero(msg); + case ErrorKind.UnexpectedEof: + throw new UnexpectedEof(msg); + case ErrorKind.BadResource: + throw new BadResource(msg); + case ErrorKind.Http: + throw new Http(msg); + } +} + +class NotFound extends Error { + constructor(msg: string) { + super(msg); + this.name = "NotFound"; + } +} +class PermissionDenied extends Error { + constructor(msg: string) { + super(msg); + this.name = "PermissionDenied"; + } +} +class ConnectionRefused extends Error { + constructor(msg: string) { + super(msg); + this.name = "ConnectionRefused"; + } +} +class ConnectionReset extends Error { + constructor(msg: string) { + super(msg); + this.name = "ConnectionReset"; + } +} +class ConnectionAborted extends Error { + constructor(msg: string) { + super(msg); + this.name = "ConnectionAborted"; + } +} +class NotConnected extends Error { + constructor(msg: string) { + super(msg); + this.name = "NotConnected"; + } +} +class AddrInUse extends Error { + constructor(msg: string) { + super(msg); + this.name = "AddrInUse"; + } +} +class AddrNotAvailable extends Error { + constructor(msg: string) { + super(msg); + this.name = "AddrNotAvailable"; + } +} +class BrokenPipe extends Error { + constructor(msg: string) { + super(msg); + this.name = "BrokenPipe"; + } +} +class AlreadyExists extends Error { + constructor(msg: string) { + super(msg); + this.name = "AlreadyExists"; + } +} +class InvalidData extends Error { + constructor(msg: string) { + super(msg); + this.name = "InvalidData"; + } +} +class TimedOut extends Error { + constructor(msg: string) { + super(msg); + this.name = "TimedOut"; + } +} +class Interrupted extends Error { + constructor(msg: string) { + super(msg); + this.name = "Interrupted"; + } +} +class WriteZero extends Error { + constructor(msg: string) { + super(msg); + this.name = "WriteZero"; + } +} +class Other extends Error { + constructor(msg: string) { + super(msg); + this.name = "Other"; + } +} +class UnexpectedEof extends Error { + constructor(msg: string) { + super(msg); + this.name = "UnexpectedEof"; + } +} +class BadResource extends Error { + constructor(msg: string) { + super(msg); + this.name = "BadResource"; + } +} +class Http extends Error { + constructor(msg: string) { + super(msg); + this.name = "Http"; + } +} + +export const Err = { + NotFound: NotFound, + PermissionDenied: PermissionDenied, + ConnectionRefused: ConnectionRefused, + ConnectionReset: ConnectionReset, + ConnectionAborted: ConnectionAborted, + NotConnected: NotConnected, + AddrInUse: AddrInUse, + AddrNotAvailable: AddrNotAvailable, + BrokenPipe: BrokenPipe, + AlreadyExists: AlreadyExists, + InvalidData: InvalidData, + TimedOut: TimedOut, + Interrupted: Interrupted, + WriteZero: WriteZero, + Other: Other, + UnexpectedEof: UnexpectedEof, + BadResource: BadResource, + Http: Http +}; diff --git a/cli/js/event_target.ts b/cli/js/event_target.ts index 495c8a0429..daa73eb231 100644 --- a/cli/js/event_target.ts +++ b/cli/js/event_target.ts @@ -1,6 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import * as domTypes from "./dom_types.ts"; -import { DenoError, ErrorKind } from "./errors.ts"; import { hasOwnProperty, requiredArguments } from "./util.ts"; import { getRoot, @@ -134,17 +133,15 @@ export class EventTarget implements domTypes.EventTarget { } if (event.dispatched || !event.initialized) { - throw new DenoError( - ErrorKind.InvalidData, - "Tried to dispatch an uninitialized event" - ); + // TODO(bartlomieju): very likely that different error + // should be thrown here (DOMException?) + throw new TypeError("Tried to dispatch an uninitialized event"); } if (event.eventPhase !== domTypes.EventPhase.NONE) { - throw new DenoError( - ErrorKind.InvalidData, - "Tried to dispatch a dispatching event" - ); + // TODO(bartlomieju): very likely that different error + // should be thrown here (DOMException?) + throw new TypeError("Tried to dispatch a dispatching event"); } return eventTargetHelpers.dispatch(this_, event); @@ -418,7 +415,9 @@ const eventTargetHelpers = { try { listener.handleEvent(eventImpl); } catch (error) { - throw new DenoError(ErrorKind.Interrupted, error.message); + // TODO(bartlomieju): very likely that different error + // should be thrown here (DOMException?) + throw new Error(error.message); } eventImpl.inPassiveListener = false; diff --git a/cli/js/fetch_test.ts b/cli/js/fetch_test.ts index c63d055012..2912d5d2de 100644 --- a/cli/js/fetch_test.ts +++ b/cli/js/fetch_test.ts @@ -16,8 +16,7 @@ testPerm({ net: true }, async function fetchConnectionError(): Promise { } catch (err_) { err = err_; } - assertEquals(err.kind, Deno.ErrorKind.Http); - assertEquals(err.name, "Http"); + assert(err instanceof Deno.Err.Http); assertStrContains(err.message, "error trying to connect"); }); @@ -34,7 +33,7 @@ test(async function fetchPerm(): Promise { } catch (err_) { err = err_; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -107,8 +106,7 @@ testPerm({ net: true }, async function fetchEmptyInvalid(): Promise { } catch (err_) { err = err_; } - assertEquals(err.kind, Deno.ErrorKind.UrlParse); - assertEquals(err.name, "UrlParse"); + assert(err instanceof URIError); }); testPerm({ net: true }, async function fetchMultipartFormDataSuccess(): Promise< diff --git a/cli/js/files_test.ts b/cli/js/files_test.ts index 03e4d00e92..f71bfecc0b 100644 --- a/cli/js/files_test.ts +++ b/cli/js/files_test.ts @@ -79,7 +79,7 @@ testPerm({ write: false }, async function writePermFailure(): Promise { err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); } }); @@ -136,8 +136,7 @@ testPerm({ read: false }, async function readPermFailure(): Promise { await Deno.open("cli/tests/fixture.json", "r"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -209,7 +208,7 @@ testPerm( err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); } } @@ -380,8 +379,8 @@ testPerm({ read: true }, async function seekMode(): Promise { err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.InvalidSeekMode); - assertEquals(err.name, "InvalidSeekMode"); + assert(err instanceof TypeError); + assertStrContains(err.message, "Invalid seek mode"); // We should still be able to read the file // since it is still open. diff --git a/cli/js/lib.deno.ns.d.ts b/cli/js/lib.deno.ns.d.ts index b5a469f0b1..fda2270a81 100644 --- a/cli/js/lib.deno.ns.d.ts +++ b/cli/js/lib.deno.ns.d.ts @@ -602,19 +602,19 @@ declare namespace Deno { write(p: Uint8Array): Promise; /** _grow() grows the buffer to guarantee space for n more bytes. * It returns the index where bytes should be written. - * If the buffer can't grow it will throw with ErrTooLarge. + * If the buffer can't grow it will throw with Error. */ private _grow; /** grow() grows the buffer's capacity, if necessary, to guarantee space for * another n bytes. After grow(n), at least n bytes can be written to the * buffer without another allocation. If n is negative, grow() will panic. If - * the buffer can't grow it will throw ErrTooLarge. + * the buffer can't grow it will throw Error. * Based on https://golang.org/pkg/bytes/#Buffer.Grow */ grow(n: number): void; /** readFrom() reads data from r until EOF and appends it to the buffer, * growing the buffer as needed. It returns the number of bytes read. If the - * buffer becomes too large, readFrom will panic with ErrTooLarge. + * buffer becomes too large, readFrom will panic with Error. * Based on https://golang.org/pkg/bytes/#Buffer.ReadFrom */ readFrom(r: Reader): Promise; @@ -1204,55 +1204,64 @@ declare namespace Deno { */ export function applySourceMap(location: Location): Location; - /** A Deno specific error. The `kind` property is set to a specific error code - * which can be used to in application logic. - * - * try { - * somethingThatMightThrow(); - * } catch (e) { - * if ( - * e instanceof Deno.DenoError && - * e.kind === Deno.ErrorKind.NotFound - * ) { - * console.error("NotFound error!"); - * } - * } - * - */ - export class DenoError extends Error { - readonly kind: T; - constructor(kind: T, msg: string); - } - export enum ErrorKind { - NotFound = 1, - PermissionDenied = 2, - ConnectionRefused = 3, - ConnectionReset = 4, - ConnectionAborted = 5, - NotConnected = 6, - AddrInUse = 7, - AddrNotAvailable = 8, - BrokenPipe = 9, - AlreadyExists = 10, - WouldBlock = 11, - InvalidInput = 12, - InvalidData = 13, - TimedOut = 14, - Interrupted = 15, - WriteZero = 16, - Other = 17, - UnexpectedEof = 18, - BadResource = 19, - UrlParse = 20, - Http = 21, - TooLarge = 22, - InvalidSeekMode = 23, - UnixError = 24, - InvalidPath = 25, - ImportPrefixMissing = 26, - Diagnostic = 27, - JSError = 28 + /* eslint-disable @typescript-eslint/no-unused-vars */ + namespace Err { + class NotFound extends Error { + constructor(msg: string); + } + class PermissionDenied extends Error { + constructor(msg: string); + } + class ConnectionRefused extends Error { + constructor(msg: string); + } + class ConnectionReset extends Error { + constructor(msg: string); + } + class ConnectionAborted extends Error { + constructor(msg: string); + } + class NotConnected extends Error { + constructor(msg: string); + } + class AddrInUse extends Error { + constructor(msg: string); + } + class AddrNotAvailable extends Error { + constructor(msg: string); + } + class BrokenPipe extends Error { + constructor(msg: string); + } + class AlreadyExists extends Error { + constructor(msg: string); + } + class InvalidData extends Error { + constructor(msg: string); + } + class TimedOut extends Error { + constructor(msg: string); + } + class Interrupted extends Error { + constructor(msg: string); + } + class WriteZero extends Error { + constructor(msg: string); + } + class Other extends Error { + constructor(msg: string); + } + class UnexpectedEof extends Error { + constructor(msg: string); + } + class BadResource extends Error { + constructor(msg: string); + } + class Http extends Error { + constructor(msg: string); + } } + /* eslint-enable @typescript-eslint/no-unused-vars */ /** UNSTABLE: potentially want names to overlap more with browser. * diff --git a/cli/js/link_test.ts b/cli/js/link_test.ts index aada34b848..2292071376 100644 --- a/cli/js/link_test.ts +++ b/cli/js/link_test.ts @@ -43,8 +43,7 @@ testPerm({ read: true, write: true }, function linkSyncExists(): void { err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.AlreadyExists); - assertEquals(err.name, "AlreadyExists"); + assert(err instanceof Deno.Err.AlreadyExists); }); testPerm({ read: true, write: true }, function linkSyncNotFound(): void { @@ -59,8 +58,7 @@ testPerm({ read: true, write: true }, function linkSyncNotFound(): void { err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm({ read: false, write: true }, function linkSyncReadPerm(): void { @@ -70,7 +68,7 @@ testPerm({ read: false, write: true }, function linkSyncReadPerm(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -81,7 +79,7 @@ testPerm({ read: true, write: false }, function linkSyncWritePerm(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); diff --git a/cli/js/make_temp_test.ts b/cli/js/make_temp_test.ts index f6bf59d32d..06bfe03738 100644 --- a/cli/js/make_temp_test.ts +++ b/cli/js/make_temp_test.ts @@ -23,8 +23,7 @@ testPerm({ write: true }, function makeTempDirSyncSuccess(): void { } catch (err_) { err = err_; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); test(function makeTempDirSyncPerm(): void { @@ -35,7 +34,7 @@ test(function makeTempDirSyncPerm(): void { } catch (err_) { err = err_; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -61,8 +60,7 @@ testPerm({ write: true }, async function makeTempDirSuccess(): Promise { } catch (err_) { err = err_; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm({ write: true }, function makeTempFileSyncSuccess(): void { @@ -88,8 +86,7 @@ testPerm({ write: true }, function makeTempFileSyncSuccess(): void { } catch (err_) { err = err_; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); test(function makeTempFileSyncPerm(): void { @@ -100,7 +97,7 @@ test(function makeTempFileSyncPerm(): void { } catch (err_) { err = err_; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -127,6 +124,5 @@ testPerm({ write: true }, async function makeTempFileSuccess(): Promise { } catch (err_) { err = err_; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); diff --git a/cli/js/mkdir_test.ts b/cli/js/mkdir_test.ts index dad61c1a47..856cbdeb5b 100644 --- a/cli/js/mkdir_test.ts +++ b/cli/js/mkdir_test.ts @@ -25,7 +25,7 @@ testPerm({ write: false }, function mkdirSyncPerm(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -45,8 +45,7 @@ testPerm({ write: true }, function mkdirErrIfExists(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.AlreadyExists); - assertEquals(err.name, "AlreadyExists"); + assert(err instanceof Deno.Err.AlreadyExists); }); testPerm({ read: true, write: true }, function mkdirSyncRecursive(): void { diff --git a/cli/js/net_test.ts b/cli/js/net_test.ts index 68b1918b9b..a2f086f0a5 100644 --- a/cli/js/net_test.ts +++ b/cli/js/net_test.ts @@ -20,15 +20,14 @@ testPerm({ net: true }, async function netCloseWhileAccept(): Promise { err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.Other); + assert(err instanceof Error); assertEquals(err.message, "Listener has been closed"); }); testPerm({ net: true }, async function netConcurrentAccept(): Promise { const listener = Deno.listen({ port: 4502 }); let acceptErrCount = 0; - const checkErr = (e: Deno.DenoError): void => { - assertEquals(e.kind, Deno.ErrorKind.Other); + const checkErr = (e: Error): void => { if (e.message === "Listener has been closed") { assertEquals(acceptErrCount, 1); } else if (e.message === "Another accept task is ongoing") { @@ -170,8 +169,7 @@ testPerm({ net: true }, async function netDoubleCloseRead() { err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.NotConnected); - assertEquals(err.name, "NotConnected"); + assert(err instanceof Deno.Err.NotConnected); closeDeferred.resolve(); listener.close(); conn.close(); @@ -205,8 +203,7 @@ testPerm({ net: true }, async function netCloseWriteSuccess() { err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.BrokenPipe); - assertEquals(err.name, "BrokenPipe"); + assert(err instanceof Deno.Err.BrokenPipe); closeDeferred.resolve(); listener.close(); conn.close(); @@ -232,8 +229,7 @@ testPerm({ net: true }, async function netDoubleCloseWrite() { err = e; } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.NotConnected); - assertEquals(err.name, "NotConnected"); + assert(err instanceof Deno.Err.NotConnected); closeDeferred.resolve(); listener.close(); conn.close(); diff --git a/cli/js/os.ts b/cli/js/os.ts index 554d4f78d7..275dbdf1d5 100644 --- a/cli/js/os.ts +++ b/cli/js/os.ts @@ -1,7 +1,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import * as dispatch from "./dispatch.ts"; import { sendSync } from "./dispatch_json.ts"; -import { ErrorKind } from "./errors.ts"; +import { Err } from "./errors.ts"; import * as util from "./util.ts"; /** Check if running in terminal. @@ -193,7 +193,7 @@ export function dir(kind: DirKind): string | null { try { return sendSync(dispatch.OP_GET_DIR, { kind }); } catch (error) { - if (error.kind == ErrorKind.PermissionDenied) { + if (error instanceof Err.PermissionDenied) { throw error; } return null; diff --git a/cli/js/os_test.ts b/cli/js/os_test.ts index a461ba63ef..fa4bf636b3 100644 --- a/cli/js/os_test.ts +++ b/cli/js/os_test.ts @@ -31,7 +31,7 @@ test(function envPermissionDenied1(): void { err = e; } assertNotEquals(err, undefined); - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -43,7 +43,7 @@ test(function envPermissionDenied2(): void { err = e; } assertNotEquals(err, undefined); - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -262,7 +262,7 @@ testPerm({ env: true }, function getDir(): void { testPerm({}, function getDirWithoutPermission(): void { assertThrows( () => Deno.dir("home"), - Deno.DenoError, + Deno.Err.PermissionDenied, `run again with the --allow-env flag` ); }); @@ -277,7 +277,7 @@ testPerm({ env: false }, function execPathPerm(): void { Deno.execPath(); } catch (err) { caughtError = true; - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); } assert(caughtError); @@ -293,7 +293,7 @@ testPerm({ env: false }, function hostnamePerm(): void { Deno.hostname(); } catch (err) { caughtError = true; - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); } assert(caughtError); diff --git a/cli/js/permissions_test.ts b/cli/js/permissions_test.ts index d63dddb15c..6d79cfec0f 100644 --- a/cli/js/permissions_test.ts +++ b/cli/js/permissions_test.ts @@ -31,18 +31,26 @@ for (const grant of knownPermissions) { } test(async function permissionInvalidName(): Promise { + let thrown = false; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any await Deno.permissions.query({ name: "foo" as any }); } catch (e) { - assert(e.name === "Other"); + thrown = true; + assert(e instanceof Error); + } finally { + assert(thrown); } }); test(async function permissionNetInvalidUrl(): Promise { + let thrown = false; try { await Deno.permissions.query({ name: "net", url: ":" }); } catch (e) { - assert(e.name === "UrlParse"); + thrown = true; + assert(e instanceof URIError); + } finally { + assert(thrown); } }); diff --git a/cli/js/process_test.ts b/cli/js/process_test.ts index dce4d99188..51ba8bfb3a 100644 --- a/cli/js/process_test.ts +++ b/cli/js/process_test.ts @@ -6,16 +6,7 @@ import { assertEquals, assertStrContains } from "./test_util.ts"; -const { - kill, - run, - DenoError, - ErrorKind, - readFile, - open, - makeTempDir, - writeFile -} = Deno; +const { kill, run, readFile, open, makeTempDir, writeFile } = Deno; test(function runPermissions(): void { let caughtError = false; @@ -23,8 +14,7 @@ test(function runPermissions(): void { Deno.run({ args: ["python", "-c", "print('hello world')"] }); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -78,8 +68,7 @@ testPerm({ run: true }, function runNotFound(): void { error = e; } assert(error !== undefined); - assert(error instanceof DenoError); - assertEquals(error.kind, ErrorKind.NotFound); + assert(error instanceof Deno.Err.NotFound); }); testPerm( @@ -332,8 +321,7 @@ if (Deno.build.os !== "win") { Deno.kill(Deno.pid, Deno.Signal.SIGCONT); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -370,8 +358,7 @@ if (Deno.build.os !== "win") { } assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.InvalidInput); - assertEquals(err.name, "InvalidInput"); + assert(err instanceof TypeError); p.close(); }); diff --git a/cli/js/read_dir_test.ts b/cli/js/read_dir_test.ts index 77d2cbfe25..4496d74475 100644 --- a/cli/js/read_dir_test.ts +++ b/cli/js/read_dir_test.ts @@ -32,8 +32,7 @@ testPerm({ read: false }, function readDirSyncPerm(): void { Deno.readDirSync("tests/"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -46,7 +45,7 @@ testPerm({ read: true }, function readDirSyncNotDir(): void { src = Deno.readDirSync("cli/tests/fixture.json"); } catch (err) { caughtError = true; - assertEquals(err.kind, Deno.ErrorKind.Other); + assert(err instanceof Error); } assert(caughtError); assertEquals(src, undefined); @@ -60,7 +59,7 @@ testPerm({ read: true }, function readDirSyncNotFound(): void { src = Deno.readDirSync("bad_dir_name"); } catch (err) { caughtError = true; - assertEquals(err.kind, Deno.ErrorKind.NotFound); + assert(err instanceof Deno.Err.NotFound); } assert(caughtError); assertEquals(src, undefined); @@ -77,8 +76,7 @@ testPerm({ read: false }, async function readDirPerm(): Promise { await Deno.readDir("tests/"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); diff --git a/cli/js/read_file_test.ts b/cli/js/read_file_test.ts index d40ea1b7b9..726f084139 100644 --- a/cli/js/read_file_test.ts +++ b/cli/js/read_file_test.ts @@ -16,8 +16,7 @@ testPerm({ read: false }, function readFileSyncPerm(): void { Deno.readFileSync("cli/tests/fixture.json"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -29,7 +28,7 @@ testPerm({ read: true }, function readFileSyncNotFound(): void { data = Deno.readFileSync("bad_filename"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); + assert(e instanceof Deno.Err.NotFound); } assert(caughtError); assert(data === undefined); @@ -50,8 +49,7 @@ testPerm({ read: false }, async function readFilePerm(): Promise { await Deno.readFile("cli/tests/fixture.json"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); diff --git a/cli/js/read_link_test.ts b/cli/js/read_link_test.ts index c8db1cb581..6f028c08d5 100644 --- a/cli/js/read_link_test.ts +++ b/cli/js/read_link_test.ts @@ -21,8 +21,7 @@ testPerm({ read: false }, async function readlinkSyncPerm(): Promise { Deno.readlinkSync("/symlink"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -34,7 +33,7 @@ testPerm({ read: true }, function readlinkSyncNotFound(): void { data = Deno.readlinkSync("bad_filename"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); + assert(e instanceof Deno.Err.NotFound); } assert(caughtError); assertEquals(data, undefined); @@ -62,8 +61,7 @@ testPerm({ read: false }, async function readlinkPerm(): Promise { await Deno.readlink("/symlink"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); diff --git a/cli/js/realpath_test.ts b/cli/js/realpath_test.ts index 7443c78973..6dfec45fc8 100644 --- a/cli/js/realpath_test.ts +++ b/cli/js/realpath_test.ts @@ -1,5 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { testPerm, assert, assertEquals } from "./test_util.ts"; +import { testPerm, assert } from "./test_util.ts"; testPerm({ read: true }, function realpathSyncSuccess(): void { const incompletePath = "cli/tests/fixture.json"; @@ -31,8 +31,7 @@ testPerm({ read: false }, function realpathSyncPerm(): void { Deno.realpathSync("some_file"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -43,7 +42,7 @@ testPerm({ read: true }, function realpathSyncNotFound(): void { Deno.realpathSync("bad_filename"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); + assert(e instanceof Deno.Err.NotFound); } assert(caughtError); }); @@ -81,8 +80,7 @@ testPerm({ read: false }, async function realpathPerm(): Promise { await Deno.realpath("some_file"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -93,7 +91,7 @@ testPerm({ read: true }, async function realpathNotFound(): Promise { await Deno.realpath("bad_filename"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); + assert(e instanceof Deno.Err.NotFound); } assert(caughtError); }); diff --git a/cli/js/remove_test.ts b/cli/js/remove_test.ts index d686d1314b..cb89ea1a96 100644 --- a/cli/js/remove_test.ts +++ b/cli/js/remove_test.ts @@ -18,8 +18,7 @@ testPerm({ write: true, read: true }, function removeSyncDirSuccess(): void { err = e; } // Directory is gone - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm({ write: true, read: true }, function removeSyncFileSuccess(): void { @@ -39,8 +38,7 @@ testPerm({ write: true, read: true }, function removeSyncFileSuccess(): void { err = e; } // File is gone - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm({ write: true, read: true }, function removeSyncFail(): void { @@ -61,8 +59,7 @@ testPerm({ write: true, read: true }, function removeSyncFail(): void { err = e; } // TODO(ry) Is Other really the error we should get here? What would Go do? - assertEquals(err.kind, Deno.ErrorKind.Other); - assertEquals(err.name, "Other"); + assert(err instanceof Error); // NON-EXISTENT DIRECTORY/FILE try { // Non-existent @@ -70,8 +67,7 @@ testPerm({ write: true, read: true }, function removeSyncFail(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm( @@ -86,7 +82,6 @@ testPerm( errOnWindows = err; } if (Deno.build.os === "win") { - assertEquals(errOnWindows.kind, Deno.ErrorKind.Other); assertEquals(errOnWindows.message, "Not implemented"); } else { const pathInfo = Deno.lstatSync(danglingSymlinkPath); @@ -98,8 +93,7 @@ testPerm( } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } } ); @@ -121,7 +115,6 @@ testPerm( errOnWindows = err; } if (Deno.build.os === "win") { - assertEquals(errOnWindows.kind, Deno.ErrorKind.Other); assertEquals(errOnWindows.message, "Not implemented"); } else { const symlinkPathInfo = Deno.statSync(validSymlinkPath); @@ -134,8 +127,7 @@ testPerm( err = e; } Deno.removeSync(filePath); - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } } ); @@ -147,7 +139,7 @@ testPerm({ write: false }, function removeSyncPerm(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -166,8 +158,8 @@ testPerm({ write: true, read: true }, function removeAllSyncDirSuccess(): void { err = e; } // Directory is gone - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); + // REMOVE NON-EMPTY DIRECTORY path = Deno.makeTempDirSync() + "/dir/subdir"; const subPath = path + "/subsubdir"; @@ -185,8 +177,7 @@ testPerm({ write: true, read: true }, function removeAllSyncDirSuccess(): void { err = e; } // Directory is gone - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm( @@ -208,8 +199,7 @@ testPerm( err = e; } // File is gone - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } ); @@ -222,8 +212,7 @@ testPerm({ write: true }, function removeAllSyncFail(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm({ write: false }, function removeAllSyncPerm(): void { @@ -233,7 +222,7 @@ testPerm({ write: false }, function removeAllSyncPerm(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -256,8 +245,7 @@ testPerm( err = e; } // Directory is gone - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } ); @@ -280,8 +268,7 @@ testPerm( err = e; } // File is gone - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } ); @@ -304,8 +291,7 @@ testPerm({ write: true, read: true }, async function removeFail(): Promise< } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.Other); - assertEquals(err.name, "Other"); + assert(err instanceof Error); // NON-EXISTENT DIRECTORY/FILE try { // Non-existent @@ -313,8 +299,7 @@ testPerm({ write: true, read: true }, async function removeFail(): Promise< } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm( @@ -329,7 +314,6 @@ testPerm( errOnWindows = e; } if (Deno.build.os === "win") { - assertEquals(errOnWindows.kind, Deno.ErrorKind.Other); assertEquals(errOnWindows.message, "Not implemented"); } else { const pathInfo = Deno.lstatSync(danglingSymlinkPath); @@ -341,8 +325,7 @@ testPerm( } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } } ); @@ -364,7 +347,6 @@ testPerm( errOnWindows = e; } if (Deno.build.os === "win") { - assertEquals(errOnWindows.kind, Deno.ErrorKind.Other); assertEquals(errOnWindows.message, "Not implemented"); } else { const symlinkPathInfo = Deno.statSync(validSymlinkPath); @@ -377,8 +359,7 @@ testPerm( err = e; } Deno.removeSync(filePath); - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } } ); @@ -390,7 +371,7 @@ testPerm({ write: false }, async function removePerm(): Promise { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -411,8 +392,8 @@ testPerm( err = e; } // Directory is gone - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); + // REMOVE NON-EMPTY DIRECTORY path = Deno.makeTempDirSync() + "/dir/subdir"; const subPath = path + "/subsubdir"; @@ -430,8 +411,7 @@ testPerm( err = e; } // Directory is gone - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } ); @@ -454,8 +434,7 @@ testPerm( err = e; } // File is gone - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } ); @@ -468,8 +447,7 @@ testPerm({ write: true }, async function removeAllFail(): Promise { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); }); testPerm({ write: false }, async function removeAllPerm(): Promise { @@ -479,6 +457,6 @@ testPerm({ write: false }, async function removeAllPerm(): Promise { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); diff --git a/cli/js/rename_test.ts b/cli/js/rename_test.ts index 9c60e4d8cf..3673d84894 100644 --- a/cli/js/rename_test.ts +++ b/cli/js/rename_test.ts @@ -17,7 +17,7 @@ testPerm({ read: true, write: true }, function renameSyncSuccess(): void { oldPathInfo = Deno.statSync(oldpath); } catch (e) { caughtErr = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); + assert(e instanceof Deno.Err.NotFound); } assert(caughtErr); assertEquals(oldPathInfo, undefined); @@ -32,7 +32,7 @@ testPerm({ read: false, write: true }, function renameSyncReadPerm(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -45,7 +45,7 @@ testPerm({ read: true, write: false }, function renameSyncWritePerm(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -67,7 +67,7 @@ testPerm({ read: true, write: true }, async function renameSuccess(): Promise< oldPathInfo = Deno.statSync(oldpath); } catch (e) { caughtErr = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); + assert(e instanceof Deno.Err.NotFound); } assert(caughtErr); assertEquals(oldPathInfo, undefined); diff --git a/cli/js/stat_test.ts b/cli/js/stat_test.ts index bce5449acf..3914f877ca 100644 --- a/cli/js/stat_test.ts +++ b/cli/js/stat_test.ts @@ -23,8 +23,7 @@ testPerm({ read: false }, async function statSyncPerm(): Promise { Deno.statSync("README.md"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -37,8 +36,7 @@ testPerm({ read: true }, async function statSyncNotFound(): Promise { badInfo = Deno.statSync("bad_file_name"); } catch (err) { caughtError = true; - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } assert(caughtError); @@ -65,8 +63,7 @@ testPerm({ read: false }, async function lstatSyncPerm(): Promise { Deno.lstatSync("README.md"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -79,8 +76,7 @@ testPerm({ read: true }, async function lstatSyncNotFound(): Promise { badInfo = Deno.lstatSync("bad_file_name"); } catch (err) { caughtError = true; - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } assert(caughtError); @@ -107,8 +103,7 @@ testPerm({ read: false }, async function statPerm(): Promise { await Deno.stat("README.md"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -121,8 +116,7 @@ testPerm({ read: true }, async function statNotFound(): Promise { badInfo = await Deno.stat("bad_file_name"); } catch (err) { caughtError = true; - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } assert(caughtError); @@ -149,8 +143,7 @@ testPerm({ read: false }, async function lstatPerm(): Promise { await Deno.lstat("README.md"); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -163,8 +156,7 @@ testPerm({ read: true }, async function lstatNotFound(): Promise { badInfo = await Deno.lstat("bad_file_name"); } catch (err) { caughtError = true; - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } assert(caughtError); diff --git a/cli/js/streams/pipe-to.ts b/cli/js/streams/pipe-to.ts index 3764e605b8..01608b955f 100644 --- a/cli/js/streams/pipe-to.ts +++ b/cli/js/streams/pipe-to.ts @@ -19,7 +19,7 @@ // import { ReadableStreamDefaultReader } from "./readable-stream-default-reader.ts"; // import { WritableStreamDefaultWriter } from "./writable-stream-default-writer.ts"; // import { PipeOptions } from "../dom_types.ts"; -// import { DenoError, ErrorKind } from "../errors.ts"; +// import { Err } from "../errors.ts"; // // add a wrapper to handle falsy rejections // interface ErrorWrapper { @@ -50,7 +50,7 @@ // abortAlgorithm = (): void => { // // TODO this should be a DOMException, // // https://github.com/stardazed/sd-streams/blob/master/packages/streams/src/pipe-to.ts#L38 -// const error = new DenoError(ErrorKind.AbortError, "Aborted"); +// const error = new Err.Aborted("Aborted"); // const actions: Array<() => Promise> = []; // if (preventAbort === false) { // actions.push(() => { diff --git a/cli/js/symlink_test.ts b/cli/js/symlink_test.ts index b25c2e9c79..b89b718b36 100644 --- a/cli/js/symlink_test.ts +++ b/cli/js/symlink_test.ts @@ -15,7 +15,6 @@ testPerm({ read: true, write: true }, function symlinkSyncSuccess(): void { } if (errOnWindows) { assertEquals(Deno.build.os, "win"); - assertEquals(errOnWindows.kind, Deno.ErrorKind.Other); assertEquals(errOnWindows.message, "Not implemented"); } else { const newNameInfoLStat = Deno.lstatSync(newname); @@ -32,7 +31,7 @@ test(function symlinkSyncPerm(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -69,7 +68,6 @@ testPerm({ read: true, write: true }, async function symlinkSuccess(): Promise< errOnWindows = e; } if (errOnWindows) { - assertEquals(errOnWindows.kind, Deno.ErrorKind.Other); assertEquals(errOnWindows.message, "Not implemented"); } else { const newNameInfoLStat = Deno.lstatSync(newname); diff --git a/cli/js/text_encoding.ts b/cli/js/text_encoding.ts index ceb2f3fdc4..0709e7123f 100644 --- a/cli/js/text_encoding.ts +++ b/cli/js/text_encoding.ts @@ -27,7 +27,6 @@ import * as base64 from "./base64.ts"; import { decodeUtf8 } from "./decode_utf8.ts"; import * as domTypes from "./dom_types.ts"; import { encodeUtf8 } from "./encode_utf8.ts"; -import { DenoError, ErrorKind } from "./errors.ts"; const CONTINUE = null; const END_OF_STREAM = -1; @@ -105,10 +104,7 @@ export function atob(s: string): string { const rem = s.length % 4; if (rem === 1 || /[^+/0-9A-Za-z]/.test(s)) { // TODO: throw `DOMException` - throw new DenoError( - ErrorKind.InvalidInput, - "The string to be decoded is not correctly encoded" - ); + throw new TypeError("The string to be decoded is not correctly encoded"); } // base64-js requires length exactly times of 4 @@ -130,8 +126,7 @@ export function btoa(s: string): string { for (let i = 0; i < s.length; i++) { const charCode = s[i].charCodeAt(0); if (charCode > 0xff) { - throw new DenoError( - ErrorKind.InvalidInput, + throw new TypeError( "The string to be encoded contains characters " + "outside of the Latin1 range." ); diff --git a/cli/js/text_encoding_test.ts b/cli/js/text_encoding_test.ts index 2422f86f6b..28f23511a0 100644 --- a/cli/js/text_encoding_test.ts +++ b/cli/js/text_encoding_test.ts @@ -59,7 +59,7 @@ test(function btoaFailed(): void { err = e; } assert(!!err); - assertEquals(err.name, "InvalidInput"); + assert(err instanceof TypeError); }); test(function textDecoder2(): void { diff --git a/cli/js/tls_test.ts b/cli/js/tls_test.ts index ac59a2eb9a..dabbb2c899 100644 --- a/cli/js/tls_test.ts +++ b/cli/js/tls_test.ts @@ -13,7 +13,7 @@ test(async function connectTLSNoPerm(): Promise { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -28,7 +28,7 @@ test(async function connectTLSCertFileNoReadPerm(): Promise { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -51,8 +51,7 @@ testPerm( } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); try { Deno.listenTLS({ @@ -62,8 +61,7 @@ testPerm( } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.NotFound); - assertEquals(err.name, "NotFound"); + assert(err instanceof Deno.Err.NotFound); } ); @@ -79,7 +77,7 @@ testPerm({ net: true }, async function listenTLSNoReadPerm(): Promise { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -108,8 +106,7 @@ testPerm( } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.Other); - assertEquals(err.name, "Other"); + assert(err instanceof Error); } ); @@ -138,8 +135,7 @@ testPerm( } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.Other); - assertEquals(err.name, "Other"); + assert(err instanceof Error); } ); diff --git a/cli/js/truncate_test.ts b/cli/js/truncate_test.ts index c8809df9e5..42583354c2 100644 --- a/cli/js/truncate_test.ts +++ b/cli/js/truncate_test.ts @@ -1,5 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { testPerm, assertEquals } from "./test_util.ts"; +import { testPerm, assertEquals, assert } from "./test_util.ts"; function readDataSync(name: string): string { const data = Deno.readFileSync(name); @@ -58,7 +58,7 @@ testPerm({ write: false }, function truncateSyncPerm(): void { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); @@ -69,6 +69,6 @@ testPerm({ write: false }, async function truncatePerm(): Promise { } catch (e) { err = e; } - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assert(err instanceof Deno.Err.PermissionDenied); assertEquals(err.name, "PermissionDenied"); }); diff --git a/cli/js/utime_test.ts b/cli/js/utime_test.ts index 72a4a64778..c7e4293bf6 100644 --- a/cli/js/utime_test.ts +++ b/cli/js/utime_test.ts @@ -1,5 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { testPerm, assert, assertEquals } from "./test_util.ts"; +import { testPerm, assert } from "./test_util.ts"; // Allow 10 second difference. // Note this might not be enough for FAT (but we are not testing on such fs). @@ -78,8 +78,7 @@ testPerm({ read: true, write: true }, function utimeSyncNotFound(): void { Deno.utimeSync("/baddir", atime, mtime); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); - assertEquals(e.name, "NotFound"); + assert(e instanceof Deno.Err.NotFound); } assert(caughtError); }); @@ -93,8 +92,7 @@ testPerm({ read: true, write: false }, function utimeSyncPerm(): void { Deno.utimeSync("/some_dir", atime, mtime); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -159,8 +157,7 @@ testPerm({ read: true, write: true }, async function utimeNotFound(): Promise< await Deno.utime("/baddir", atime, mtime); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); - assertEquals(e.name, "NotFound"); + assert(e instanceof Deno.Err.NotFound); } assert(caughtError); }); @@ -176,8 +173,7 @@ testPerm({ read: true, write: false }, async function utimeSyncPerm(): Promise< await Deno.utime("/some_dir", atime, mtime); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); diff --git a/cli/js/write_file_test.ts b/cli/js/write_file_test.ts index 2b952655f5..9f58f44602 100644 --- a/cli/js/write_file_test.ts +++ b/cli/js/write_file_test.ts @@ -22,8 +22,7 @@ testPerm({ write: true }, function writeFileSyncFail(): void { Deno.writeFileSync(filename, data); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); - assertEquals(e.name, "NotFound"); + assert(e instanceof Deno.Err.NotFound); } assert(caughtError); }); @@ -38,8 +37,7 @@ testPerm({ write: false }, function writeFileSyncPerm(): void { Deno.writeFileSync(filename, data); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -66,8 +64,7 @@ testPerm({ read: true, write: true }, function writeFileSyncCreate(): void { Deno.writeFileSync(filename, data, { create: false }); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); - assertEquals(e.name, "NotFound"); + assert(e instanceof Deno.Err.NotFound); } assert(caughtError); @@ -128,8 +125,7 @@ testPerm( await Deno.writeFile(filename, data); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); - assertEquals(e.name, "NotFound"); + assert(e instanceof Deno.Err.NotFound); } assert(caughtError); } @@ -147,8 +143,7 @@ testPerm({ read: true, write: false }, async function writeFilePerm(): Promise< await Deno.writeFile(filename, data); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(e.name, "PermissionDenied"); + assert(e instanceof Deno.Err.PermissionDenied); } assert(caughtError); }); @@ -180,8 +175,7 @@ testPerm({ read: true, write: true }, async function writeFileCreate(): Promise< await Deno.writeFile(filename, data, { create: false }); } catch (e) { caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); - assertEquals(e.name, "NotFound"); + assert(e instanceof Deno.Err.NotFound); } assert(caughtError); diff --git a/cli/msg.rs b/cli/msg.rs index 643c63869a..146f45ea54 100644 --- a/cli/msg.rs +++ b/cli/msg.rs @@ -1,41 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -// Warning! The values in this enum are duplicated in js/errors.ts -// Update carefully! -#[allow(non_camel_case_types)] -#[repr(i8)] -#[derive(Clone, Copy, PartialEq, Debug)] -pub enum ErrorKind { - NotFound = 1, - PermissionDenied = 2, - ConnectionRefused = 3, - ConnectionReset = 4, - ConnectionAborted = 5, - NotConnected = 6, - AddrInUse = 7, - AddrNotAvailable = 8, - BrokenPipe = 9, - AlreadyExists = 10, - WouldBlock = 11, - InvalidInput = 12, - InvalidData = 13, - TimedOut = 14, - Interrupted = 15, - WriteZero = 16, - Other = 17, - UnexpectedEof = 18, - BadResource = 19, - UrlParse = 20, - Http = 21, - TooLarge = 22, - InvalidSeekMode = 23, - UnixError = 24, - InvalidPath = 25, - ImportPrefixMissing = 26, - Diagnostic = 27, - JSError = 28, -} - // Warning! The values in this enum are duplicated in js/compiler.ts // Update carefully! #[allow(non_camel_case_types)] diff --git a/cli/ops/dispatch_minimal.rs b/cli/ops/dispatch_minimal.rs index 70c4af6c38..0bff571f22 100644 --- a/cli/ops/dispatch_minimal.rs +++ b/cli/ops/dispatch_minimal.rs @@ -4,8 +4,8 @@ //! alternative to flatbuffers using a very simple list of int32s to lay out //! messages. The first i32 is used to determine if a message a flatbuffer //! message or a "minimal" message. +use crate::deno_error::ErrorKind; use crate::deno_error::GetErrorKind; -use crate::msg::ErrorKind; use byteorder::{LittleEndian, WriteBytesExt}; use deno_core::Buf; use deno_core::CoreOp; @@ -124,7 +124,7 @@ where let error_record = ErrorRecord { promise_id: 0, arg: -1, - error_code: ErrorKind::InvalidInput as i32, + error_code: ErrorKind::TypeError as i32, error_message: "Unparsable control buffer" .to_string() .as_bytes() diff --git a/cli/ops/files.rs b/cli/ops/files.rs index d625d45903..9619051a71 100644 --- a/cli/ops/files.rs +++ b/cli/ops/files.rs @@ -190,7 +190,7 @@ fn op_seek( 2 => SeekFrom::End(i64::from(offset)), _ => { return Err(ErrBox::from(DenoError::new( - ErrorKind::InvalidSeekMode, + ErrorKind::TypeError, format!("Invalid seek mode: {}", whence), ))); } diff --git a/cli/ops/worker_host.rs b/cli/ops/worker_host.rs index 13d4fffffc..c3b9076732 100644 --- a/cli/ops/worker_host.rs +++ b/cli/ops/worker_host.rs @@ -2,7 +2,6 @@ use super::dispatch_json::{Deserialize, JsonOp, Value}; use crate::deno_error::DenoError; use crate::deno_error::ErrorKind; -use crate::deno_error::GetErrorKind; use crate::fmt_errors::JSError; use crate::futures::SinkExt; use crate::global_state::GlobalState; @@ -212,11 +211,17 @@ fn op_host_terminate_worker( fn serialize_worker_event(event: WorkerEvent) -> Value { match event { WorkerEvent::Message(buf) => json!({ "type": "msg", "data": buf }), - WorkerEvent::Error(error) => match error.kind() { - ErrorKind::JSError => { - let error = error.downcast::().unwrap(); - let exception: V8Exception = error.into(); - json!({ + WorkerEvent::Error(error) => { + let mut serialized_error = json!({ + "type": "error", + "error": { + "message": error.to_string(), + } + }); + + if let Ok(err) = error.downcast::() { + let exception: V8Exception = err.into(); + serialized_error = json!({ "type": "error", "error": { "message": exception.message, @@ -224,15 +229,11 @@ fn serialize_worker_event(event: WorkerEvent) -> Value { "lineNumber": exception.line_number, "columnNumber": exception.start_column, } - }) + }); } - _ => json!({ - "type": "error", - "error": { - "message": error.to_string(), - } - }), - }, + + serialized_error + } } } diff --git a/cli/tests/044_bad_resource.ts.out b/cli/tests/044_bad_resource.ts.out index 155e4396f1..92b493ca96 100644 --- a/cli/tests/044_bad_resource.ts.out +++ b/cli/tests/044_bad_resource.ts.out @@ -1,6 +1,7 @@ [WILDCARD] error: Uncaught BadResource: bad resource id -[WILDCARD]dispatch_json.ts:[WILDCARD] - at DenoError ([WILDCARD]errors.ts:[WILDCARD]) +[WILDCARD]errors.ts:[WILDCARD] + at BadResource ([WILDCARD]errors.ts:[WILDCARD]) + at constructError ([WILDCARD]errors.ts:[WILDCARD]) at unwrapResponse ([WILDCARD]dispatch_json.ts:[WILDCARD]) at sendAsync ([WILDCARD]dispatch_json.ts:[WILDCARD]) diff --git a/cli/tests/error_004_missing_module.ts.out b/cli/tests/error_004_missing_module.ts.out index a9be1419a6..492aef0e67 100644 --- a/cli/tests/error_004_missing_module.ts.out +++ b/cli/tests/error_004_missing_module.ts.out @@ -1,5 +1,6 @@ [WILDCARD]error: Uncaught NotFound: Cannot resolve module "[WILDCARD]/bad-module.ts" from "[WILDCARD]/error_004_missing_module.ts" -[WILDCARD]dispatch_json.ts:[WILDCARD] - at DenoError ([WILDCARD]errors.ts:[WILDCARD]) +[WILDCARD]errors.ts:[WILDCARD] + at NotFound ([WILDCARD]errors.ts:[WILDCARD]) + at constructError ([WILDCARD]errors.ts:[WILDCARD]) at unwrapResponse ([WILDCARD]dispatch_json.ts:[WILDCARD]) at sendAsync[WILDCARD] ([WILDCARD]dispatch_json.ts:[WILDCARD]) diff --git a/cli/tests/error_005_missing_dynamic_import.ts.out b/cli/tests/error_005_missing_dynamic_import.ts.out index 24031a61c9..3b48e4e78a 100644 --- a/cli/tests/error_005_missing_dynamic_import.ts.out +++ b/cli/tests/error_005_missing_dynamic_import.ts.out @@ -1,5 +1,6 @@ [WILDCARD]error: Uncaught NotFound: Cannot resolve module "[WILDCARD]/bad-module.ts" from "[WILDCARD]/error_005_missing_dynamic_import.ts" -[WILDCARD]dispatch_json.ts:[WILDCARD] - at DenoError ([WILDCARD]errors.ts:[WILDCARD]) +[WILDCARD]errors.ts:[WILDCARD] + at NotFound ([WILDCARD]errors.ts:[WILDCARD]) + at constructError ([WILDCARD]errors.ts:[WILDCARD]) at unwrapResponse ([WILDCARD]dispatch_json.ts:[WILDCARD]) at sendAsync[WILDCARD] ([WILDCARD]dispatch_json.ts:[WILDCARD]) diff --git a/cli/tests/error_006_import_ext_failure.ts.out b/cli/tests/error_006_import_ext_failure.ts.out index deda91c2f7..e113bc2640 100644 --- a/cli/tests/error_006_import_ext_failure.ts.out +++ b/cli/tests/error_006_import_ext_failure.ts.out @@ -1,5 +1,6 @@ [WILDCARD]error: Uncaught NotFound: Cannot resolve module "[WILDCARD]/non-existent" from "[WILDCARD]/error_006_import_ext_failure.ts" -[WILDCARD]dispatch_json.ts:[WILDCARD] - at DenoError ([WILDCARD]errors.ts:[WILDCARD]) +[WILDCARD]errors.ts:[WILDCARD] + at NotFound ([WILDCARD]errors.ts:[WILDCARD]) + at constructError ([WILDCARD]errors.ts:[WILDCARD]) at unwrapResponse ([WILDCARD]dispatch_json.ts:[WILDCARD]) at sendAsync[WILDCARD] ([WILDCARD]dispatch_json.ts:[WILDCARD]) diff --git a/cli/tests/error_011_bad_module_specifier.ts.out b/cli/tests/error_011_bad_module_specifier.ts.out index 7c100db13a..7bf7ef26a6 100644 --- a/cli/tests/error_011_bad_module_specifier.ts.out +++ b/cli/tests/error_011_bad_module_specifier.ts.out @@ -1,6 +1,6 @@ -[WILDCARD]error: Uncaught ImportPrefixMissing: relative import path "bad-module.ts" not prefixed with / or ./ or ../ Imported from "[WILDCARD]/error_011_bad_module_specifier.ts" -[WILDCARD]dispatch_json.ts:[WILDCARD] - at DenoError ($deno$/errors.ts:[WILDCARD]) +[WILDCARD]error: Uncaught URIError: relative import path "bad-module.ts" not prefixed with / or ./ or ../ Imported from "[WILDCARD]/error_011_bad_module_specifier.ts" +[WILDCARD]errors.ts:[WILDCARD] + at constructError ($deno$/errors.ts:[WILDCARD]) at unwrapResponse ($deno$/dispatch_json.ts:[WILDCARD]) at sendSync ($deno$/dispatch_json.ts:[WILDCARD]) at resolveModules ($deno$/compiler_imports.ts:[WILDCARD]) diff --git a/cli/tests/error_012_bad_dynamic_import_specifier.ts.out b/cli/tests/error_012_bad_dynamic_import_specifier.ts.out index 095ca497bf..9f41f9b287 100644 --- a/cli/tests/error_012_bad_dynamic_import_specifier.ts.out +++ b/cli/tests/error_012_bad_dynamic_import_specifier.ts.out @@ -1,6 +1,6 @@ -[WILDCARD]error: Uncaught ImportPrefixMissing: relative import path "bad-module.ts" not prefixed with / or ./ or ../ Imported from "[WILDCARD]/error_012_bad_dynamic_import_specifier.ts" -[WILDCARD]dispatch_json.ts:[WILDCARD] - at DenoError ($deno$/errors.ts:[WILDCARD]) +[WILDCARD]error: Uncaught URIError: relative import path "bad-module.ts" not prefixed with / or ./ or ../ Imported from "[WILDCARD]/error_012_bad_dynamic_import_specifier.ts" +[WILDCARD]errors.ts:[WILDCARD] + at constructError ($deno$/errors.ts:[WILDCARD]) at unwrapResponse ($deno$/dispatch_json.ts:[WILDCARD]) at sendSync ($deno$/dispatch_json.ts:[WILDCARD]) at resolveModules ($deno$/compiler_imports.ts:[WILDCARD]) diff --git a/cli/tests/error_type_definitions.ts.out b/cli/tests/error_type_definitions.ts.out index d2c6096ace..04b012eadf 100644 --- a/cli/tests/error_type_definitions.ts.out +++ b/cli/tests/error_type_definitions.ts.out @@ -1,6 +1,6 @@ -[WILDCARD]error: Uncaught ImportPrefixMissing: relative import path "baz" not prefixed with / or ./ or ../ Imported from "[WILDCARD]/type_definitions/bar.d.ts" -[WILDCARD]dispatch_json.ts:[WILDCARD] - at DenoError ($deno$/errors.ts:[WILDCARD]) +[WILDCARD]error: Uncaught URIError: relative import path "baz" not prefixed with / or ./ or ../ Imported from "[WILDCARD]/type_definitions/bar.d.ts" +[WILDCARD]errors.ts:[WILDCARD] + at constructError ($deno$/errors.ts:[WILDCARD]) at unwrapResponse ($deno$/dispatch_json.ts:[WILDCARD]) at sendSync ($deno$/dispatch_json.ts:[WILDCARD]) at resolveModules ($deno$/compiler_imports.ts:[WILDCARD]) diff --git a/std/encoding/yaml/error.ts b/std/encoding/yaml/error.ts index 62be8b477d..7f305ccf2c 100644 --- a/std/encoding/yaml/error.ts +++ b/std/encoding/yaml/error.ts @@ -5,14 +5,12 @@ import { Mark } from "./mark.ts"; -const { DenoError, ErrorKind } = Deno; - -export class YAMLError extends DenoError { +export class YAMLError extends Error { constructor( message = "(unknown reason)", protected mark: Mark | string = "" ) { - super(ErrorKind.Other, `${message} ${mark}`); + super(`${message} ${mark}`); this.name = this.constructor.name; } diff --git a/std/fs/copy.ts b/std/fs/copy.ts index 86fac78dff..ec51784c66 100644 --- a/std/fs/copy.ts +++ b/std/fs/copy.ts @@ -29,7 +29,7 @@ async function ensureValidCopy( try { destStat = await Deno.lstat(dest); } catch (err) { - if (err instanceof Deno.DenoError && err.kind == Deno.ErrorKind.NotFound) { + if (err instanceof Deno.Err.NotFound) { return; } throw err; @@ -57,7 +57,7 @@ function ensureValidCopySync( try { destStat = Deno.lstatSync(dest); } catch (err) { - if (err instanceof Deno.DenoError && err.kind == Deno.ErrorKind.NotFound) { + if (err instanceof Deno.Err.NotFound) { return; } throw err; diff --git a/std/fs/empty_dir.ts b/std/fs/empty_dir.ts index e3d08ef70a..0ac5e6420c 100644 --- a/std/fs/empty_dir.ts +++ b/std/fs/empty_dir.ts @@ -1,14 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { join } from "../path/mod.ts"; -const { - readDir, - readDirSync, - mkdir, - mkdirSync, - remove, - removeSync, - ErrorKind -} = Deno; +const { readDir, readDirSync, mkdir, mkdirSync, remove, removeSync } = Deno; /** * Ensures that a directory is empty. * Deletes directory contents if the directory is not empty. @@ -28,7 +20,7 @@ export async function emptyDir(dir: string): Promise { } } } catch (err) { - if ((err as Deno.DenoError).kind !== ErrorKind.NotFound) { + if (!(err instanceof Deno.Err.NotFound)) { throw err; } @@ -57,7 +49,7 @@ export function emptyDirSync(dir: string): void { } } } catch (err) { - if ((err as Deno.DenoError).kind !== ErrorKind.NotFound) { + if (!(err instanceof Deno.Err.NotFound)) { throw err; } // if not exist. then create it diff --git a/std/fs/ensure_dir.ts b/std/fs/ensure_dir.ts index d4b30dd2d9..b6cc3150a3 100644 --- a/std/fs/ensure_dir.ts +++ b/std/fs/ensure_dir.ts @@ -1,6 +1,6 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { getFileInfoType } from "./utils.ts"; -const { lstat, lstatSync, mkdir, mkdirSync, ErrorKind } = Deno; +const { lstat, lstatSync, mkdir, mkdirSync } = Deno; /** * Ensures that the directory exists. @@ -16,7 +16,7 @@ export async function ensureDir(dir: string): Promise { ); } } catch (err) { - if (err instanceof Deno.DenoError && err.kind === ErrorKind.NotFound) { + if (err instanceof Deno.Err.NotFound) { // if dir not exists. then create it. await mkdir(dir, { recursive: true }); return; @@ -39,7 +39,7 @@ export function ensureDirSync(dir: string): void { ); } } catch (err) { - if (err instanceof Deno.DenoError && err.kind == ErrorKind.NotFound) { + if (err instanceof Deno.Err.NotFound) { // if dir not exists. then create it. mkdirSync(dir, { recursive: true }); return; diff --git a/std/fs/ensure_file.ts b/std/fs/ensure_file.ts index 06c65b5f77..be824b7bac 100644 --- a/std/fs/ensure_file.ts +++ b/std/fs/ensure_file.ts @@ -2,7 +2,7 @@ import * as path from "../path/mod.ts"; import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; import { getFileInfoType } from "./utils.ts"; -const { lstat, lstatSync, writeFile, writeFileSync, ErrorKind } = Deno; +const { lstat, lstatSync, writeFile, writeFileSync } = Deno; /** * Ensures that the file exists. @@ -23,7 +23,7 @@ export async function ensureFile(filePath: string): Promise { } } catch (err) { // if file not exists - if (err instanceof Deno.DenoError && err.kind === ErrorKind.NotFound) { + if (err instanceof Deno.Err.NotFound) { // ensure dir exists await ensureDir(path.dirname(filePath)); // create file @@ -54,7 +54,7 @@ export function ensureFileSync(filePath: string): void { } } catch (err) { // if file not exists - if (err instanceof Deno.DenoError && err.kind === ErrorKind.NotFound) { + if (err instanceof Deno.Err.NotFound) { // ensure dir exists ensureDirSync(path.dirname(filePath)); // create file diff --git a/std/fs/ensure_link_test.ts b/std/fs/ensure_link_test.ts index 6e9804152a..7549814a25 100644 --- a/std/fs/ensure_link_test.ts +++ b/std/fs/ensure_link_test.ts @@ -143,8 +143,7 @@ Deno.test(async function ensureLinkDirectoryIfItExist(): Promise { await assertThrowsAsync( async (): Promise => { await ensureLink(testDir, linkDir); - }, - Deno.DenoError + } // "Operation not permitted (os error 1)" // throw an local matching test // "Access is denied. (os error 5)" // throw in CI ); @@ -163,8 +162,7 @@ Deno.test(function ensureLinkSyncDirectoryIfItExist(): void { assertThrows( (): void => { ensureLinkSync(testDir, linkDir); - }, - Deno.DenoError + } // "Operation not permitted (os error 1)" // throw an local matching test // "Access is denied. (os error 5)" // throw in CI ); diff --git a/std/fs/exists.ts b/std/fs/exists.ts index 4584dbff96..2cd4151739 100644 --- a/std/fs/exists.ts +++ b/std/fs/exists.ts @@ -1,5 +1,5 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -const { lstat, lstatSync, DenoError, ErrorKind } = Deno; +const { lstat, lstatSync } = Deno; /** * Test whether or not the given path exists by checking with the file system */ @@ -7,10 +7,8 @@ export async function exists(filePath: string): Promise { return lstat(filePath) .then((): boolean => true) .catch((err: Error): boolean => { - if (err instanceof DenoError) { - if (err.kind === ErrorKind.NotFound) { - return false; - } + if (err instanceof Deno.Err.NotFound) { + return false; } throw err; @@ -25,10 +23,8 @@ export function existsSync(filePath: string): boolean { lstatSync(filePath); return true; } catch (err) { - if (err instanceof DenoError) { - if (err.kind === ErrorKind.NotFound) { - return false; - } + if (err instanceof Deno.Err.NotFound) { + return false; } throw err; } diff --git a/std/fs/expand_glob.ts b/std/fs/expand_glob.ts index aabf4a8a1b..61fca96028 100644 --- a/std/fs/expand_glob.ts +++ b/std/fs/expand_glob.ts @@ -10,9 +10,7 @@ import { } from "../path/mod.ts"; import { WalkInfo, walk, walkSync } from "./walk.ts"; import { assert } from "../testing/asserts.ts"; -const { ErrorKind, cwd, stat, statSync } = Deno; -type ErrorKind = Deno.ErrorKind; -type DenoError = Deno.DenoError; +const { cwd, stat, statSync } = Deno; type FileInfo = Deno.FileInfo; export interface ExpandGlobOptions extends GlobOptions { @@ -45,7 +43,7 @@ function split(path: string): SplitPath { } function throwUnlessNotFound(error: Error): void { - if ((error as DenoError).kind != ErrorKind.NotFound) { + if (!(error instanceof Deno.Err.NotFound)) { throw error; } } diff --git a/std/fs/walk_test.ts b/std/fs/walk_test.ts index 4984546f21..f99f82eb51 100644 --- a/std/fs/walk_test.ts +++ b/std/fs/walk_test.ts @@ -1,7 +1,5 @@ -const { DenoError, ErrorKind, cwd, chdir, makeTempDir, mkdir, open } = Deno; +const { cwd, chdir, makeTempDir, mkdir, open } = Deno; const { remove } = Deno; -type ErrorKind = Deno.ErrorKind; -type DenoError = Deno.DenoError; import { walk, walkSync, WalkOptions, WalkInfo } from "./walk.ts"; import { assertEquals, assertThrowsAsync } from "../testing/asserts.ts"; @@ -235,10 +233,9 @@ testWalk( testWalk( async (_d: string): Promise => {}, async function nonexistentRoot(): Promise { - const error = (await assertThrowsAsync(async () => { + await assertThrowsAsync(async () => { await walkArray("nonexistent"); - }, DenoError)) as DenoError; - assertEquals(error.kind, ErrorKind.NotFound); + }, Deno.Err.NotFound); } ); diff --git a/std/http/file_server.ts b/std/http/file_server.ts index aa0ff49daa..acc3a20cd2 100755 --- a/std/http/file_server.ts +++ b/std/http/file_server.ts @@ -6,7 +6,7 @@ // TODO Add tests like these: // https://github.com/indexzero/http-server/blob/master/test/http-server-test.js -const { ErrorKind, DenoError, args, stat, readDir, open, exit } = Deno; +const { args, stat, readDir, open, exit } = Deno; import { posix } from "../path/mod.ts"; import { listenAndServe, @@ -163,7 +163,7 @@ async function serveDir( } async function serveFallback(req: ServerRequest, e: Error): Promise { - if (e instanceof DenoError && e.kind === ErrorKind.NotFound) { + if (e instanceof Deno.Err.NotFound) { return { status: 404, body: encoder.encode("Not found") diff --git a/std/node/module.ts b/std/node/module.ts index 547c76bab1..aecf03ede6 100644 --- a/std/node/module.ts +++ b/std/node/module.ts @@ -57,7 +57,7 @@ function stat(filename: string): StatResult { if (statCache !== null) statCache.set(filename, result); return result; } catch (e) { - if (e.kind === Deno.ErrorKind.PermissionDenied) { + if (e instanceof Deno.Err.PermissionDenied) { throw new Error("CJS loader requires --allow-read."); } return -1; diff --git a/std/node/process_test.ts b/std/node/process_test.ts index 51dbcd630b..545b6ce23f 100644 --- a/std/node/process_test.ts +++ b/std/node/process_test.ts @@ -24,13 +24,11 @@ test({ () => { process.chdir("non-existent-directory-name"); }, - Deno.DenoError, + Deno.Err.NotFound, "file" // On every OS Deno returns: "No such file" except for Windows, where it's: // "The system cannot find the file specified. (os error 2)" so "file" is // the only common string here. - // TODO(rsp): Crazy idea: 404 for things like this? - // It would be nice to have error codes like 404 or 403 in addition to strings. ); } }); diff --git a/std/path/glob.ts b/std/path/glob.ts index a079f448f0..8eb106b251 100644 --- a/std/path/glob.ts +++ b/std/path/glob.ts @@ -3,8 +3,6 @@ import { globrex } from "./globrex.ts"; import { join, normalize } from "./mod.ts"; import { assert } from "../testing/asserts.ts"; -const { DenoError, ErrorKind } = Deno; - export interface GlobOptions { extended?: boolean; globstar?: boolean; @@ -91,10 +89,7 @@ export function normalizeGlob( { globstar = false }: GlobOptions = {} ): string { if (!!glob.match(/\0/g)) { - throw new DenoError( - ErrorKind.InvalidPath, - `Glob contains invalid characters: "${glob}"` - ); + throw new Error(`Glob contains invalid characters: "${glob}"`); } if (!globstar) { return normalize(glob); diff --git a/std/testing/runner.ts b/std/testing/runner.ts index 8d6501e029..772e027241 100755 --- a/std/testing/runner.ts +++ b/std/testing/runner.ts @@ -3,7 +3,7 @@ import { parse } from "../flags/mod.ts"; import { ExpandGlobOptions, expandGlob } from "../fs/mod.ts"; import { isWindows, join } from "../path/mod.ts"; -const { DenoError, ErrorKind, args, cwd, exit } = Deno; +const { args, cwd, exit } = Deno; const DIR_GLOBS = [join("**", "?(*_)test.{js,ts}")]; @@ -182,7 +182,7 @@ export async function runTestModules({ if (moduleCount == 0) { const noneFoundMessage = "No matching test modules found."; if (!allowNone) { - throw new DenoError(ErrorKind.NotFound, noneFoundMessage); + throw new Deno.Err.NotFound(noneFoundMessage); } else if (!disableLog) { console.log(noneFoundMessage); }