Continue and Break on Try/Catch (#7683)

Co-authored-by: sholderbach <sholderbach@users.noreply.github.com>
Fixes https://github.com/nushell/nushell/issues/7656
This commit is contained in:
Amirhossein Akhlaghpour 2023-01-05 15:41:51 -05:00 committed by GitHub
parent 771270d526
commit 9b617de6f0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 59 additions and 0 deletions

View File

@ -57,6 +57,13 @@ impl Command for Try {
match result {
Err(error) | Ok(PipelineData::Value(Value::Error { error }, ..)) => {
if let nu_protocol::ShellError::Break(_) = error {
return Err(error);
} else if let nu_protocol::ShellError::Continue(_) = error {
return Err(error);
} else if let nu_protocol::ShellError::Return(_, _) = error {
return Err(error);
}
if let Some(catch_block) = catch_block {
let catch_block = engine_state.get_block(catch_block.block_id);
let err_value = Value::Error { error };

View File

@ -49,3 +49,55 @@ fn external_failed_should_be_catched() {
assert!(output.out.contains("fail"));
}
#[test]
fn loop_try_break_should_be_successful() {
let output = nu!(
cwd: ".",
"loop { try { echo 'successful'; break } catch { echo 'failed'; continue } }"
);
assert_eq!(output.out, "successful");
}
#[test]
fn loop_catch_break_should_show_failed() {
let output = nu!(
cwd: ".",
"loop {
try { invalid 1;
continue; } catch { echo 'failed'; break }
}
"
);
assert_eq!(output.out, "failed");
}
#[test]
fn loop_try_ignores_continue() {
let output = nu!(
cwd: ".",
"mut total = 0;
for i in 0..10 {
try { if ($i mod 2) == 0 {
continue;}
$total += 1
} catch { echo 'failed'; break }
}
echo $total
"
);
assert_eq!(output.out, "5");
}
#[test]
fn loop_try_break_on_command_should_show_successful() {
let output = nu!(
cwd: ".",
"loop { try { ls; break } catch { echo 'failed';continue }}"
);
assert!(!output.out.contains("failed"));
}