From a59477205dbf114d12d2ab9099d4bd13004a1b96 Mon Sep 17 00:00:00 2001 From: Devyn Cairns Date: Fri, 13 Sep 2024 00:07:22 -0700 Subject: [PATCH] Fix `try`: Add `set_last_error()` to `prepare_error_handler()` for IR eval (#13838) # Description Fixes a bug with `set_last_error()` introduced by @IanManske not being called during the jump to an error handler in IR eval. Without this, `$env.LAST_EXIT_CODE` wasn't getting set in the `catch` block for an external. # Tests + Formatting Added a `tests/eval` test to cover this in both IR and non-IR eval --- crates/nu-engine/src/eval_ir.rs | 2 ++ tests/eval/mod.rs | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/crates/nu-engine/src/eval_ir.rs b/crates/nu-engine/src/eval_ir.rs index b6f5287196..7cc4e0267d 100644 --- a/crates/nu-engine/src/eval_ir.rs +++ b/crates/nu-engine/src/eval_ir.rs @@ -246,6 +246,8 @@ fn prepare_error_handler( ) { if let Some(reg_id) = error_handler.error_register { if let Some(error) = error { + // Stack state has to be updated for stuff like LAST_EXIT_CODE + ctx.stack.set_last_error(&error.item); // Create the error value and put it in the register ctx.put_reg( reg_id, diff --git a/tests/eval/mod.rs b/tests/eval/mod.rs index e9afd401e9..f8996f0a3e 100644 --- a/tests/eval/mod.rs +++ b/tests/eval/mod.rs @@ -451,6 +451,14 @@ fn try_catch_with_non_literal_closure() { ) } +#[test] +fn try_catch_external() { + test_eval( + r#"try { nu -c 'exit 1' } catch { $env.LAST_EXIT_CODE }"#, + Eq("1"), + ) +} + #[test] fn row_condition() { test_eval(