Browse Source

Add a JsError::from_rust constructor to create native errors from Rust (#3921)

* Add a JsError::from_std constructor to create native errors from Rust

* Address comment
pull/3944/head
Hans Larsen 5 months ago committed by GitHub
parent
commit
6f1d7d11ce
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 26
      core/engine/src/error.rs

26
core/engine/src/error.rs

@ -1,7 +1,5 @@
//! Error-related types and conversions.
use std::{error, fmt};
use crate::{
builtins::{error::ErrorObject, Array},
js_string,
@ -12,6 +10,7 @@ use crate::{
};
use boa_gc::{custom_trace, Finalize, Trace};
use boa_macros::js_str;
use std::{error, fmt};
use thiserror::Error;
/// Create an opaque error object from a value or string literal.
@ -188,6 +187,29 @@ impl JsError {
}
}
/// Creates a new `JsError` from a Rust standard error `err`.
/// This will create a new `JsNativeError` with the message of the standard error.
///
/// # Examples
///
/// ```
/// # use boa_engine::JsError;
/// let error = std::io::Error::new(std::io::ErrorKind::Other, "oh no!");
/// let js_error: JsError = JsError::from_rust(error);
///
/// assert_eq!(js_error.as_native().unwrap().message(), "oh no!");
/// assert!(js_error.as_native().unwrap().cause().is_none());
/// ```
#[must_use]
pub fn from_rust(err: impl error::Error) -> Self {
let mut native_err = JsNativeError::error().with_message(err.to_string());
if let Some(source) = err.source() {
native_err = native_err.with_cause(Self::from_rust(source));
}
Self::from_native(native_err)
}
/// Creates a new `JsError` from an opaque error `value`.
///
/// # Examples

Loading…
Cancel
Save