refactor: remove unneeded ErrorKinds (#3936)

This commit is contained in:
Bartek Iwańczuk 2020-02-21 10:36:13 -05:00 committed by GitHub
parent d9efb8c02a
commit dd8a109481
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
66 changed files with 553 additions and 620 deletions

View file

@ -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::<DenoError>().map(Get::kind))
.or_else(|| self.downcast_ref::<Diagnostic>().map(Get::kind))
.or_else(|| self.downcast_ref::<reqwest::Error>().map(Get::kind))
.or_else(|| self.downcast_ref::<ImportMapError>().map(Get::kind))
.or_else(|| self.downcast_ref::<io::Error>().map(Get::kind))
.or_else(|| self.downcast_ref::<JSError>().map(Get::kind))
.or_else(|| self.downcast_ref::<ModuleResolutionError>().map(Get::kind))
.or_else(|| self.downcast_ref::<StaticError>().map(Get::kind))
.or_else(|| self.downcast_ref::<url::ParseError>().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");
}
}

View file

@ -251,7 +251,7 @@ impl SourceFileFetcher {
fn fetch_local_file(&self, module_url: &Url) -> Result<SourceFile, ErrBox> {
let filepath = module_url.to_file_path().map_err(|()| {
ErrBox::from(DenoError::new(
ErrorKind::InvalidPath,
ErrorKind::URIError,
"File URL contains invalid path".to_owned(),
))
})?;

View file

@ -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<number> {

View file

@ -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<void> {
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<void> {

View file

@ -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<void> {
} 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<void> {
@ -145,6 +143,6 @@ testPerm({ write: false }, async function chmodPerm(): Promise<void> {
} catch (e) {
err = e;
}
assertEquals(err.kind, Deno.ErrorKind.PermissionDenied);
assert(err instanceof Deno.Err.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
});

View file

@ -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 });
});

View file

@ -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);
});

View file

@ -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,

View file

@ -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");

View file

@ -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;

View file

@ -2,7 +2,6 @@ import {
test,
testPerm,
assert,
assertEquals,
assertMatch,
unreachable
} from "./test_util.ts";
@ -31,5 +30,4 @@ test(async function malformedJsonControlBuffer(): Promise<void> {
const resJson = JSON.parse(resText) as any;
assert(!resJson.ok);
assert(resJson.err);
assertEquals(resJson.err!.kind, Deno.ErrorKind.InvalidInput);
});

View file

@ -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<number, util.Resolvable<RecordMinimal>>();
// 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;
}

View file

@ -36,9 +36,7 @@ test(async function malformedMinimalControlBuffer(): Promise<void> {
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");
});

View file

@ -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<T extends ErrorKind> 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
};

View file

@ -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;

View file

@ -16,8 +16,7 @@ testPerm({ net: true }, async function fetchConnectionError(): Promise<void> {
} 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<void> {
} 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<void> {
} 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<

View file

@ -79,7 +79,7 @@ testPerm({ write: false }, async function writePermFailure(): Promise<void> {
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<void> {
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<void> {
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.

View file

@ -602,19 +602,19 @@ declare namespace Deno {
write(p: Uint8Array): Promise<number>;
/** _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<number>;
@ -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<T extends ErrorKind> 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.
*

View file

@ -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");
});

View file

@ -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<void> {
} 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<void> {
} catch (err_) {
err = err_;
}
assertEquals(err.kind, Deno.ErrorKind.NotFound);
assertEquals(err.name, "NotFound");
assert(err instanceof Deno.Err.NotFound);
});

View file

@ -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 {

View file

@ -20,15 +20,14 @@ testPerm({ net: true }, async function netCloseWhileAccept(): Promise<void> {
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<void> {
const listener = Deno.listen({ port: 4502 });
let acceptErrCount = 0;
const checkErr = (e: Deno.DenoError<Deno.ErrorKind>): 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();

View file

@ -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;

View file

@ -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);

View file

@ -31,18 +31,26 @@ for (const grant of knownPermissions) {
}
test(async function permissionInvalidName(): Promise<void> {
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<void> {
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);
}
});

View file

@ -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();
});

View file

@ -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<void> {
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);
});

View file

@ -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<void> {
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);
});

View file

@ -21,8 +21,7 @@ testPerm({ read: false }, async function readlinkSyncPerm(): Promise<void> {
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<void> {
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);
});

View file

@ -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<void> {
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<void> {
await Deno.realpath("bad_filename");
} catch (e) {
caughtError = true;
assertEquals(e.kind, Deno.ErrorKind.NotFound);
assert(e instanceof Deno.Err.NotFound);
}
assert(caughtError);
});

View file

@ -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<void> {
} 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<void> {
} 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<void> {
@ -479,6 +457,6 @@ testPerm({ write: false }, async function removeAllPerm(): Promise<void> {
} catch (e) {
err = e;
}
assertEquals(err.kind, Deno.ErrorKind.PermissionDenied);
assert(err instanceof Deno.Err.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
});

View file

@ -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);

View file

@ -23,8 +23,7 @@ testPerm({ read: false }, async function statSyncPerm(): Promise<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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);

View file

@ -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<void>> = [];
// if (preventAbort === false) {
// actions.push(() => {

View file

@ -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);

View file

@ -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."
);

View file

@ -59,7 +59,7 @@ test(function btoaFailed(): void {
err = e;
}
assert(!!err);
assertEquals(err.name, "InvalidInput");
assert(err instanceof TypeError);
});
test(function textDecoder2(): void {

View file

@ -13,7 +13,7 @@ test(async function connectTLSNoPerm(): Promise<void> {
} 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<void> {
} 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<void> {
} 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);
}
);

View file

@ -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<void> {
} catch (e) {
err = e;
}
assertEquals(err.kind, Deno.ErrorKind.PermissionDenied);
assert(err instanceof Deno.Err.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
});

View file

@ -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);
});

View file

@ -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);

View file

@ -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)]

View file

@ -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()

View file

@ -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),
)));
}

View file

@ -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::<JSError>().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::<JSError>() {
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
}
}
}

View file

@ -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])

View file

@ -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])

View file

@ -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])

View file

@ -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])

View file

@ -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])

View file

@ -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])

View file

@ -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])

View file

@ -5,14 +5,12 @@
import { Mark } from "./mark.ts";
const { DenoError, ErrorKind } = Deno;
export class YAMLError extends DenoError<typeof ErrorKind.Other> {
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;
}

View file

@ -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;

View file

@ -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<void> {
}
}
} catch (err) {
if ((err as Deno.DenoError<Deno.ErrorKind>).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<Deno.ErrorKind>).kind !== ErrorKind.NotFound) {
if (!(err instanceof Deno.Err.NotFound)) {
throw err;
}
// if not exist. then create it

View file

@ -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<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.
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;

View file

@ -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<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
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

View file

@ -143,8 +143,7 @@ Deno.test(async function ensureLinkDirectoryIfItExist(): Promise<void> {
await assertThrowsAsync(
async (): Promise<void> => {
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
);

View file

@ -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<boolean> {
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;
}

View file

@ -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<ErrorKind>;
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;
}
}

View file

@ -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<ErrorKind>;
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<void> => {},
async function nonexistentRoot(): Promise<void> {
const error = (await assertThrowsAsync(async () => {
await assertThrowsAsync(async () => {
await walkArray("nonexistent");
}, DenoError)) as DenoError;
assertEquals(error.kind, ErrorKind.NotFound);
}, Deno.Err.NotFound);
}
);

View file

@ -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<Response> {
if (e instanceof DenoError && e.kind === ErrorKind.NotFound) {
if (e instanceof Deno.Err.NotFound) {
return {
status: 404,
body: encoder.encode("Not found")

View file

@ -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;

View file

@ -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.
);
}
});

View file

@ -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);

View file

@ -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);
}