Add label rendering to try/catch rendered errors (#14477)

<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->



# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

Before this PR, you can access rendered error values that are raised in
a `try/catch` block by accessing the `rendered` element of the catch
error value:
```
$ try { ls nonexist.txt } catch {|e| print "my cool error:" $e.rendered }
my cool error:
nu:🐚:directory_not_found

  × Directory not found
  help: /home/rose/nonexist.txt does not exist
```

However, the rendered errors don't include the labels present in the
real rendered error, which would look like this:
```
$ ls nonexist.txt
Error: nu:🐚:directory_not_found

  × Directory not found
   ╭─[entry #46:1:4]
 1 │ ls nonexist.txt
   ·    ──────┬─────
   ·          ╰── directory not found
   ╰────
  help: /home/rose/nonexist.txt does not exist
```

After this PR, the rendered error includes the labels:

```
$ try { ls nonexist.txt } catch {|e| print "my cool error:" $e.rendered }
my cool error:
Error: nu:🐚:directory_not_found

  × Directory not found
   ╭─[entry #4:1:10]
 1 │ try { ls nonexist.txt } catch {|e| print "my cool error:" $e.rendered }
   ·          ──────┬─────
   ·                ╰── directory not found
   ╰────
  help: /home/rose/nonexist.txt does not exist
```

This change is accomplished by using the standard error formatting code
to render an error. This respects the error theme as before without any
extra scaffolding, but it means that e.g., the terminal size is also
respected. I think this is fine because the way the error is rendered
already changed based on config, and I think that a "rendered" error
should give back _exactly_ what would be shown to the user anyway.

@fdncred, let me know if you have any concerns with the way this is
handled since you were the one who implemented this feature in the first
place.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

The `rendered` element of the `try`/`catch` error record now includes
labels in the error output.

# 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
> ```
-->
- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`


# 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.
-->
N/A
This commit is contained in:
132ikl 2024-11-29 20:02:26 -05:00 committed by GitHub
parent e17f6d654c
commit e1f74a6d57
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 8 additions and 53 deletions

View File

@ -107,11 +107,7 @@ fn run_catch(
if let Some(catch) = catch { if let Some(catch) = catch {
stack.set_last_error(&error); stack.set_last_error(&error);
let fancy_errors = match engine_state.get_config().error_style { let error = error.into_value(&StateWorkingSet::new(engine_state), span);
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) {

View File

@ -4,7 +4,9 @@ use nu_path::{expand_path_with, AbsolutePathBuf};
use nu_protocol::{ use nu_protocol::{
ast::{Bits, Block, Boolean, CellPath, Comparison, Math, Operator}, ast::{Bits, Block, Boolean, CellPath, Comparison, Math, Operator},
debugger::DebugContext, debugger::DebugContext,
engine::{Argument, Closure, EngineState, ErrorHandler, Matcher, Redirection, Stack}, engine::{
Argument, Closure, EngineState, ErrorHandler, Matcher, Redirection, Stack, StateWorkingSet,
},
ir::{Call, DataSlice, Instruction, IrAstRef, IrBlock, Literal, RedirectMode}, ir::{Call, DataSlice, Instruction, IrAstRef, IrBlock, Literal, RedirectMode},
ByteStreamSource, DataSource, DeclId, ErrSpan, Flag, IntoPipelineData, IntoSpanned, ListStream, ByteStreamSource, DataSource, DeclId, ErrSpan, Flag, IntoPipelineData, IntoSpanned, ListStream,
OutDest, PipelineData, PipelineMetadata, PositionalArg, Range, Record, RegId, ShellError, OutDest, PipelineData, PipelineMetadata, PositionalArg, Range, Record, RegId, ShellError,
@ -220,17 +222,8 @@ 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( prepare_error_handler(ctx, error_handler, Some(err.into_spanned(*span)));
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
@ -255,7 +248,6 @@ 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 {
@ -266,7 +258,7 @@ fn prepare_error_handler(
reg_id, reg_id,
error error
.item .item
.into_value(error.span, fancy_errors) .into_value(&StateWorkingSet::new(ctx.engine_state), error.span)
.into_pipeline_data(), .into_pipeline_data(),
); );
} else { } else {

View File

@ -139,23 +139,6 @@ 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

View File

@ -1479,15 +1479,14 @@ impl ShellError {
} }
} }
pub fn into_value(self, span: Span, fancy_errors: bool) -> Value { pub fn into_value(self, working_set: &StateWorkingSet, span: Span) -> 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.clone(), span), "raw" => Value::error(self.clone(), span),
// "labeled_error" => Value::string(LabeledError::from_diagnostic_and_render(self.clone()), span), "rendered" => Value::string(format_shell_error(working_set, &self), 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), "json" => Value::string(serde_json::to_string(&self).expect("Could not serialize error"), span),
}; };
@ -1507,21 +1506,6 @@ 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 {