From ee7478781e7ce3c39ba33c01dc32902e7f667633 Mon Sep 17 00:00:00 2001 From: Ian Manske Date: Thu, 1 Aug 2024 20:57:46 -0700 Subject: [PATCH] Add exit code to error record given to `catch` --- crates/nu-cmd-lang/src/core_commands/try_.rs | 28 ++++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/crates/nu-cmd-lang/src/core_commands/try_.rs b/crates/nu-cmd-lang/src/core_commands/try_.rs index 14c72276bb..7f5072a3f3 100644 --- a/crates/nu-cmd-lang/src/core_commands/try_.rs +++ b/crates/nu-cmd-lang/src/core_commands/try_.rs @@ -106,6 +106,7 @@ fn run_catch( let error = intercept_block_control(error)?; if let Some(catch) = catch { + stack.set_last_error(&error); let error = err_to_record(error, span); let block = engine_state.get_block(catch.block_id); // Put the error value in the positional closure var @@ -133,23 +134,28 @@ fn run_catch( /// `Err` when flow control to bubble up with `?` fn intercept_block_control(error: ShellError) -> Result { match error { - nu_protocol::ShellError::Break { .. } => Err(error), - nu_protocol::ShellError::Continue { .. } => Err(error), - nu_protocol::ShellError::Return { .. } => Err(error), + ShellError::Break { .. } => Err(error), + ShellError::Continue { .. } => Err(error), + ShellError::Return { .. } => Err(error), _ => Ok(error), } } /// Convert from `error` to [`Value::Record`] so the error information can be easily accessed in catch. fn err_to_record(error: ShellError, head: Span) -> Value { - Value::record( - record! { - "msg" => Value::string(error.to_string(), head), - "debug" => Value::string(format!("{error:?}"), head), - "raw" => Value::error(error, head), - }, - head, - ) + let exit_code = error.external_exit_code(); + + let mut record = record! { + "msg" => Value::string(error.to_string(), head), + "debug" => Value::string(format!("{error:?}"), head), + "raw" => Value::error(error, head), + }; + + if let Some(code) = exit_code { + record.push("exit_code", Value::int(code.item.into(), code.span)); + } + + Value::record(record, head) } #[cfg(test)]