mirror of
https://github.com/nushell/nushell
synced 2024-12-26 21:13:19 +00:00
add rendered and json error messages in try/catch (#14082)
# Description This PR adds a couple more options for dealing with try/catch errors. It adds a `json` version of the error and a `rendered` version of the error. It also respects the error_style configuration point. ![image](https://github.com/user-attachments/assets/32574f07-f511-40c0-8b57-de5f6f13a9c4) # User-Facing Changes <!-- List of all changes that impact the user experience here. This helps us keep track of breaking changes. --> # Tests + Formatting <!-- Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to check that you're using the standard code style - `cargo test --workspace` to check that all tests pass (on Windows make sure to [enable developer mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging)) - `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the tests for the standard library > **Note** > from `nushell` you can also use the `toolkit` as follows > ```bash > use toolkit.nu # or use an `env_change` hook to activate it automatically > toolkit check pr > ``` --> # After Submitting <!-- If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date. -->
This commit is contained in:
parent
7f2f67238f
commit
8c8f795e9e
6 changed files with 75 additions and 5 deletions
|
@ -107,7 +107,11 @@ fn run_catch(
|
||||||
|
|
||||||
if let Some(catch) = catch {
|
if let Some(catch) = catch {
|
||||||
stack.set_last_error(&error);
|
stack.set_last_error(&error);
|
||||||
let error = error.into_value(span);
|
let fancy_errors = match engine_state.get_config().error_style {
|
||||||
|
nu_protocol::ErrorStyle::Fancy => true,
|
||||||
|
nu_protocol::ErrorStyle::Plain => false,
|
||||||
|
};
|
||||||
|
let error = error.into_value(span, fancy_errors);
|
||||||
let block = engine_state.get_block(catch.block_id);
|
let block = engine_state.get_block(catch.block_id);
|
||||||
// Put the error value in the positional closure var
|
// Put the error value in the positional closure var
|
||||||
if let Some(var) = block.signature.get_positional(0) {
|
if let Some(var) = block.signature.get_positional(0) {
|
||||||
|
|
|
@ -126,3 +126,20 @@ fn prints_only_if_last_pipeline() {
|
||||||
let actual = nu!("try { ['should not print'] | every 1 }; 'last value'");
|
let actual = nu!("try { ['should not print'] | every 1 }; 'last value'");
|
||||||
assert_eq!(actual.out, "last value");
|
assert_eq!(actual.out, "last value");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_error_columns() {
|
||||||
|
let actual = nu!(" try { non_existent_command } catch {|err| $err} | columns | to json -r");
|
||||||
|
assert_eq!(
|
||||||
|
actual.out,
|
||||||
|
"[\"msg\",\"debug\",\"raw\",\"rendered\",\"json\"]"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_json_error() {
|
||||||
|
let actual = nu!("try { non_existent_command } catch {|err| $err} | get json | from json | update labels.span {{start: 0 end: 0}} | to json -r");
|
||||||
|
assert_eq!(
|
||||||
|
actual.out, "{\"msg\":\"External command failed\",\"labels\":[{\"text\":\"Command `non_existent_command` not found\",\"span\":{\"start\":0,\"end\":0}}],\"code\":\"nu::shell::external_command\",\"url\":null,\"help\":\"`non_existent_command` is neither a Nushell built-in or a known external command\",\"inner\":[]}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
|
@ -220,8 +220,17 @@ fn eval_ir_block_impl<D: DebugContext>(
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if let Some(error_handler) = ctx.stack.error_handlers.pop(ctx.error_handler_base) {
|
if let Some(error_handler) = ctx.stack.error_handlers.pop(ctx.error_handler_base) {
|
||||||
|
let fancy_errors = match ctx.engine_state.get_config().error_style {
|
||||||
|
nu_protocol::ErrorStyle::Fancy => true,
|
||||||
|
nu_protocol::ErrorStyle::Plain => false,
|
||||||
|
};
|
||||||
// If an error handler is set, branch there
|
// If an error handler is set, branch there
|
||||||
prepare_error_handler(ctx, error_handler, Some(err.into_spanned(*span)));
|
prepare_error_handler(
|
||||||
|
ctx,
|
||||||
|
error_handler,
|
||||||
|
Some(err.into_spanned(*span)),
|
||||||
|
fancy_errors,
|
||||||
|
);
|
||||||
pc = error_handler.handler_index;
|
pc = error_handler.handler_index;
|
||||||
} else {
|
} else {
|
||||||
// If not, exit the block with the error
|
// If not, exit the block with the error
|
||||||
|
@ -246,6 +255,7 @@ fn prepare_error_handler(
|
||||||
ctx: &mut EvalContext<'_>,
|
ctx: &mut EvalContext<'_>,
|
||||||
error_handler: ErrorHandler,
|
error_handler: ErrorHandler,
|
||||||
error: Option<Spanned<ShellError>>,
|
error: Option<Spanned<ShellError>>,
|
||||||
|
fancy_errors: bool,
|
||||||
) {
|
) {
|
||||||
if let Some(reg_id) = error_handler.error_register {
|
if let Some(reg_id) = error_handler.error_register {
|
||||||
if let Some(error) = error {
|
if let Some(error) = error {
|
||||||
|
@ -254,7 +264,10 @@ fn prepare_error_handler(
|
||||||
// Create the error value and put it in the register
|
// Create the error value and put it in the register
|
||||||
ctx.put_reg(
|
ctx.put_reg(
|
||||||
reg_id,
|
reg_id,
|
||||||
error.item.into_value(error.span).into_pipeline_data(),
|
error
|
||||||
|
.item
|
||||||
|
.into_value(error.span, fancy_errors)
|
||||||
|
.into_pipeline_data(),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// Set the register to empty
|
// Set the register to empty
|
||||||
|
|
|
@ -35,6 +35,7 @@ miette = { workspace = true, features = ["fancy-no-backtrace"] }
|
||||||
num-format = { workspace = true }
|
num-format = { workspace = true }
|
||||||
rmp-serde = { workspace = true, optional = true }
|
rmp-serde = { workspace = true, optional = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
thiserror = "1.0"
|
thiserror = "1.0"
|
||||||
typetag = "0.2"
|
typetag = "0.2"
|
||||||
os_pipe = { workspace = true, features = ["io_safety"] }
|
os_pipe = { workspace = true, features = ["io_safety"] }
|
||||||
|
|
|
@ -139,6 +139,23 @@ impl LabeledError {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn render_error_to_string(diag: impl miette::Diagnostic, fancy_errors: bool) -> String {
|
||||||
|
let theme = if fancy_errors {
|
||||||
|
miette::GraphicalTheme::unicode()
|
||||||
|
} else {
|
||||||
|
miette::GraphicalTheme::none()
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut out = String::new();
|
||||||
|
miette::GraphicalReportHandler::new()
|
||||||
|
.with_width(80)
|
||||||
|
.with_theme(theme)
|
||||||
|
.render_report(&mut out, &diag)
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// Create a [`LabeledError`] from a type that implements [`miette::Diagnostic`].
|
/// Create a [`LabeledError`] from a type that implements [`miette::Diagnostic`].
|
||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
|
|
|
@ -1477,13 +1477,16 @@ impl ShellError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn into_value(self, span: Span) -> Value {
|
pub fn into_value(self, span: Span, fancy_errors: bool) -> Value {
|
||||||
let exit_code = self.external_exit_code();
|
let exit_code = self.external_exit_code();
|
||||||
|
|
||||||
let mut record = record! {
|
let mut record = record! {
|
||||||
"msg" => Value::string(self.to_string(), span),
|
"msg" => Value::string(self.to_string(), span),
|
||||||
"debug" => Value::string(format!("{self:?}"), span),
|
"debug" => Value::string(format!("{self:?}"), span),
|
||||||
"raw" => Value::error(self, span),
|
"raw" => Value::error(self.clone(), span),
|
||||||
|
// "labeled_error" => Value::string(LabeledError::from_diagnostic_and_render(self.clone()), span),
|
||||||
|
"rendered" => Value::string(ShellError::render_error_to_string(self.clone(), fancy_errors), span),
|
||||||
|
"json" => Value::string(serde_json::to_string(&self).expect("Could not serialize error"), span),
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(code) = exit_code {
|
if let Some(code) = exit_code {
|
||||||
|
@ -1502,6 +1505,21 @@ impl ShellError {
|
||||||
span,
|
span,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
pub fn render_error_to_string(diag: impl miette::Diagnostic, fancy_errors: bool) -> String {
|
||||||
|
let theme = if fancy_errors {
|
||||||
|
miette::GraphicalTheme::unicode()
|
||||||
|
} else {
|
||||||
|
miette::GraphicalTheme::none()
|
||||||
|
};
|
||||||
|
let mut out = String::new();
|
||||||
|
miette::GraphicalReportHandler::new()
|
||||||
|
.with_width(80)
|
||||||
|
.with_theme(theme)
|
||||||
|
.render_report(&mut out, &diag)
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
out
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<io::Error> for ShellError {
|
impl From<io::Error> for ShellError {
|
||||||
|
|
Loading…
Reference in a new issue