deno_error/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
#![deny(clippy::unnecessary_wraps)]
#![deny(clippy::print_stderr)]
#![deny(clippy::print_stdout)]

//! Trait and macros to represent Rust errors in JavaScript.
//!
//! ## The [`JsError`] macro
//!
//! Macro to define the `JsErrorClass` trait on a struct or enum.
//!
//! The macro does not provide functionality to related to the `get_message`
//! function, as one can combine the [`thiserror`](https://crates.io/crates/thiserror) well with this macro.
//!
//! ### Attributes
//!
//! #### `#[class]`
//! This attribute accepts 3 possible kinds of value:
//!   1. `GENERIC`, `TYPE`, and a few more that are defined in the `builtin_classes`
//!      module, without the `_ERROR` suffix.
//!   2. A text value ie `"NotFound"`. If a text value is passed that is a valid
//!      builtin (see the previous point), it will error out as the special
//!      identifiers are preferred to avoid mistakes.
//!   3. `inherit`: this will inherit the class from whatever field is marked with
//!      the `#[inherit]` attribute. Alternatively, the `#[inherit]` attribute
//!      can be omitted if only one field is present in the enum variant or struct.
//!      This value is inferred if the class attribute is missing and only a single
//!      field is present on a struct, however for enums this inferring is not done.
//!
//! #### `#[property]`
//! This attribute allows defining fields as additional properties that should be
//! defined on the JavaScript error.
//!
//! The type of the field needs to implement a `.to_string()` function for it
//! being able to be inherited.
//!
//! #### `#[inherit]`
//! This attribute allows defining a field that should be used to inherit the class
//! and properties.
//!
//! This is inferred if only one field is present in the enum variant or struct.
//!
//! The class is only inherited if the `class` attribute is set to `inherit`.
//!
//! ### Examples
//!
//! #### Basic usage
//! ```
//! #[derive(Debug, thiserror::Error, deno_error::JsError)]
//! pub enum SomeError {
//!   #[class(generic)]
//!   #[error("Failure")]
//!   Failure,
//!   #[class(inherit)]
//!   #[error(transparent)]
//!   Io(#[inherit] std::io::Error),
//! }
//! ```
//!
//! #### Top-level class
//! ```
//! #[derive(Debug, thiserror::Error, deno_error::JsError)]
//! #[class(generic)]
//! pub enum SomeError {
//!   #[error("Failure")]
//!   Failure,
//!   #[class(inherit)] // overwrite the top-level
//!   #[error(transparent)]
//!   Io(#[inherit] std::io::Error),
//! }
//! ```
//!
//! #### Defining properties
//! ```
//! #[derive(Debug, thiserror::Error, deno_error::JsError)]
//! #[class(generic)]
//! pub enum SomeError {
//!   #[class(not_supported)]
//!   #[error("Failure")]
//!   Failure {
//!     #[property]
//!     code: u32,
//!   },
//!   #[error("Warning")]
//!   Warning(#[property = "code"] u32),
//!   #[class(inherit)] // inherit properties from `std::io::Error`
//!   #[error(transparent)]
//!   Io(#[inherit] std::io::Error),
//! }
//! ```
//!
//! #### Inferred inheritance
//! ```
//! #[derive(Debug, thiserror::Error, deno_error::JsError)]
//! #[error("My io error")]
//! pub struct SomeError(std::io::Error);
//! ```
//!
//! ```
//! #[derive(Debug, thiserror::Error, deno_error::JsError)]
//! #[class(inherit)]
//! #[error("My io error")]
//! pub struct SomeError(std::io::Error);
//! ```
//!
//! ```
//! #[derive(Debug, thiserror::Error, deno_error::JsError)]
//! #[class(generic)] // don't inherit the error
//! #[error("My io error")]
//! pub struct SomeError(std::io::Error);
//! ```
//!
//! ```
//! #[derive(Debug, thiserror::Error, deno_error::JsError)]
//! #[class(type)]
//! pub enum SomeError {
//!   #[error("Failure")]
//!   Failure,
//!   #[class(inherit)]
//!   #[error(transparent)]
//!   Io(std::io::Error),
//! }
//! ```

mod error_codes;

pub use deno_error_macro::*;
pub use error_codes::*;
use std::any::Any;
use std::borrow::Cow;

/// Various built-in error classes, mainly related to the JavaScript specification.
/// May include some error classes that are non-standard.
pub mod builtin_classes {
  // keep in sync with macros/lib.rs
  pub const GENERIC_ERROR: &str = "Error";
  pub const RANGE_ERROR: &str = "RangeError";
  pub const TYPE_ERROR: &str = "TypeError";
  pub const SYNTAX_ERROR: &str = "SyntaxError";
  pub const URI_ERROR: &str = "URIError";
  pub const REFERENCE_ERROR: &str = "ReferenceError";

  /// Non-standard
  pub const NOT_SUPPORTED_ERROR: &str = "NotSupported";
}
use builtin_classes::*;

/// Trait to implement how an error should be represented in JavaScript.
///
/// **Note**:
/// it is not recommended to manually implement this type, but instead
/// rather use the [`JsError`] macro.
pub trait JsErrorClass:
  std::error::Error + Send + Sync + Any + 'static
{
  /// Represents the error class used in JavaScript side.
  fn get_class(&self) -> Cow<'static, str>;

  /// Represents the error message used in JavaScript side.
  fn get_message(&self) -> Cow<'static, str>;

  /// Additional properties that should be defined on the error in JavaScript side.
  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)>;

  fn as_any(&self) -> &dyn Any;
}

/// Macro which lets you wrap an existing error in a new error that implements
/// the [`JsErrorClass`] trait. This macro however does currently not support
/// the special identifiers that the [`JsError`] macro supports.
///
/// ## Examples
///
/// ```rust
/// # use deno_error::js_error_wrapper;
/// js_error_wrapper!(std::net::AddrParseError, JsAddrParseError, "TypeError");
/// ```
///
/// ```rust
/// # use deno_error::js_error_wrapper;
/// js_error_wrapper!(std::net::AddrParseError, JsAddrParseError, |err| {
///   // match or do some logic to get the error class
///   "TypeError"
/// });
/// ```
#[macro_export]
macro_rules! js_error_wrapper {
  ($err_path:path, $err_name:ident, $js_err_type:tt) => {
    deno_error::js_error_wrapper!($err_path, $err_name, |_error| $js_err_type);
  };
  ($err_path:path, $err_name:ident, |$inner:ident| $js_err_type:tt) => {
    #[derive(Debug)]
    pub struct $err_name(pub $err_path);
    impl From<$err_path> for $err_name {
      fn from(err: $err_path) -> Self {
        Self(err)
      }
    }
    impl $err_name {
      pub fn get_error_class(
        $inner: &$err_path,
      ) -> impl Into<std::borrow::Cow<'static, str>> {
        $js_err_type
      }
    }
    impl std::error::Error for $err_name {
      fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        std::error::Error::source(&self.0)
      }
    }
    impl std::fmt::Display for $err_name {
      fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.0, f)
      }
    }
    impl deno_error::JsErrorClass for $err_name {
      fn get_class(&self) -> std::borrow::Cow<'static, str> {
        Self::get_error_class(&self.0).into()
      }
      fn get_message(&self) -> std::borrow::Cow<'static, str> {
        self.to_string().into()
      }
      fn get_additional_properties(
        &self,
      ) -> Vec<(
        std::borrow::Cow<'static, str>,
        std::borrow::Cow<'static, str>,
      )> {
        vec![]
      }
      fn as_any(&self) -> &dyn std::any::Any {
        self
      }
    }
    impl std::ops::Deref for $err_name {
      type Target = $err_path;

      fn deref(&self) -> &Self::Target {
        &self.0
      }
    }
  };
}

impl<T: JsErrorClass> JsErrorClass for Box<T> {
  fn get_class(&self) -> Cow<'static, str> {
    (**self).get_class()
  }

  fn get_message(&self) -> Cow<'static, str> {
    (**self).get_message()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    (**self).get_additional_properties()
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl JsErrorClass for std::io::Error {
  fn get_class(&self) -> Cow<'static, str> {
    use std::io::ErrorKind::*;

    let class = match self.kind() {
      NotFound => "NotFound",
      PermissionDenied => "PermissionDenied",
      ConnectionRefused => "ConnectionRefused",
      ConnectionReset => "ConnectionReset",
      ConnectionAborted => "ConnectionAborted",
      NotConnected => "NotConnected",
      AddrInUse => "AddrInUse",
      AddrNotAvailable => "AddrNotAvailable",
      BrokenPipe => "BrokenPipe",
      AlreadyExists => "AlreadyExists",
      InvalidInput => TYPE_ERROR,
      InvalidData => "InvalidData",
      TimedOut => "TimedOut",
      Interrupted => "Interrupted",
      WriteZero => "WriteZero",
      UnexpectedEof => "UnexpectedEof",
      Other => GENERIC_ERROR,
      WouldBlock => "WouldBlock",
      kind => {
        let kind_str = kind.to_string();
        match kind_str.as_str() {
          "FilesystemLoop" => "FilesystemLoop",
          "IsADirectory" => "IsADirectory",
          "NetworkUnreachable" => "NetworkUnreachable",
          "NotADirectory" => "NotADirectory",
          _ => GENERIC_ERROR,
        }
      }
    };

    Cow::Borrowed(class)
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.to_string().into()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    get_error_code(self)
      .map(|code| vec![("code".into(), code.into())])
      .unwrap_or_default()
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl JsErrorClass for std::env::VarError {
  fn get_class(&self) -> Cow<'static, str> {
    Cow::Borrowed(match self {
      std::env::VarError::NotPresent => "NotFound",
      std::env::VarError::NotUnicode(..) => "InvalidData",
    })
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.to_string().into()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    vec![]
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl JsErrorClass for std::sync::mpsc::RecvError {
  fn get_class(&self) -> Cow<'static, str> {
    Cow::Borrowed(GENERIC_ERROR)
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.to_string().into()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    vec![]
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl JsErrorClass for std::str::Utf8Error {
  fn get_class(&self) -> Cow<'static, str> {
    Cow::Borrowed(GENERIC_ERROR)
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.to_string().into()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    vec![]
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl JsErrorClass for std::num::TryFromIntError {
  fn get_class(&self) -> Cow<'static, str> {
    Cow::Borrowed(TYPE_ERROR)
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.to_string().into()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    vec![]
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

#[cfg(all(feature = "serde", feature = "serde_json"))]
impl JsErrorClass for serde_json::Error {
  fn get_class(&self) -> Cow<'static, str> {
    use serde::de::StdError;
    use serde_json::error::*;

    match self.classify() {
      Category::Io => self
        .source()
        .and_then(|e| e.downcast_ref::<std::io::Error>())
        .unwrap()
        .get_class(),
      Category::Syntax => Cow::Borrowed(SYNTAX_ERROR),
      Category::Data => Cow::Borrowed("InvalidData"),
      Category::Eof => Cow::Borrowed("UnexpectedEof"),
    }
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.to_string().into()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    vec![] // TODO: could be io error code
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

#[cfg(feature = "url")]
impl JsErrorClass for url::ParseError {
  fn get_class(&self) -> Cow<'static, str> {
    Cow::Borrowed(URI_ERROR)
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.to_string().into()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    vec![]
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

#[cfg(feature = "tokio")]
impl<T: Send + Sync + 'static> JsErrorClass
  for tokio::sync::mpsc::error::SendError<T>
{
  fn get_class(&self) -> Cow<'static, str> {
    Cow::Borrowed(GENERIC_ERROR)
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.to_string().into()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    vec![]
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

#[cfg(feature = "tokio")]
impl JsErrorClass for tokio::task::JoinError {
  fn get_class(&self) -> Cow<'static, str> {
    Cow::Borrowed(GENERIC_ERROR)
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.to_string().into()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    vec![]
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

#[cfg(feature = "tokio")]
impl JsErrorClass for tokio::sync::broadcast::error::RecvError {
  fn get_class(&self) -> Cow<'static, str> {
    Cow::Borrowed(GENERIC_ERROR)
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.to_string().into()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    vec![]
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

#[derive(Debug)]
pub struct JsErrorBox {
  class: Cow<'static, str>,
  message: Cow<'static, str>,
  pub inner: Option<Box<dyn JsErrorClass>>,
}

impl std::fmt::Display for JsErrorBox {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}", self.message)
  }
}

impl std::error::Error for JsErrorBox {
  fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
    self.inner.as_ref().and_then(|e| e.source())
  }
}

impl JsErrorClass for JsErrorBox {
  fn get_class(&self) -> Cow<'static, str> {
    self.class.clone()
  }

  fn get_message(&self) -> Cow<'static, str> {
    self.message.clone()
  }

  fn get_additional_properties(
    &self,
  ) -> Vec<(Cow<'static, str>, Cow<'static, str>)> {
    self
      .inner
      .as_ref()
      .map(|source| source.get_additional_properties())
      .unwrap_or_default()
  }

  fn as_any(&self) -> &dyn Any {
    if let Some(err) = &self.inner {
      err.as_any()
    } else {
      self
    }
  }
}

impl JsErrorBox {
  pub fn new(
    class: impl Into<Cow<'static, str>>,
    message: impl Into<Cow<'static, str>>,
  ) -> JsErrorBox {
    JsErrorBox {
      class: class.into(),
      message: message.into(),
      inner: None,
    }
  }

  pub fn from_err<T: JsErrorClass>(err: T) -> Self {
    Self {
      class: err.get_class(),
      message: err.get_message(),
      inner: Some(Box::new(err)),
    }
  }

  pub fn generic(message: impl Into<Cow<'static, str>>) -> JsErrorBox {
    Self::new(GENERIC_ERROR, message)
  }

  pub fn type_error(message: impl Into<Cow<'static, str>>) -> JsErrorBox {
    Self::new(TYPE_ERROR, message)
  }

  pub fn range_error(message: impl Into<Cow<'static, str>>) -> JsErrorBox {
    Self::new(RANGE_ERROR, message)
  }

  pub fn uri_error(message: impl Into<Cow<'static, str>>) -> JsErrorBox {
    Self::new(URI_ERROR, message)
  }

  // Non-standard errors
  pub fn not_supported() -> JsErrorBox {
    Self::new(NOT_SUPPORTED_ERROR, "The operation is not supported")
  }
}