nushell/crates/nu-command/tests/commands/try_.rs
Reilly Wood ed1f0eb231
Make catch block a closure w/ access to error (#7228)
A small follow-up to #7221. This changes the `catch` block from a block
to a closure, so that it can access the error returned from the `try`
block. This helps with a common scenario: "the `try` block failed, and I
want to log why it failed."

### Example


![image](https://user-images.githubusercontent.com/26268125/203841966-f1f8f102-fd73-41e6-83bc-bf69ed436fa8.png)

### Future Work

Nu's closure syntax is a little awkward here; it might be nicer to allow
something like `catch err { print $err }`. We discussed this on Discord
and it will require special parser code similar to what's already done
for `for`.

I'm not feeling confident enough in my parser knowledge to make that
change; I will spend some more time looking at the `for` code but I
doubt I will be able to implement anything in the next few days.
Volunteers welcome.
2022-11-25 07:02:20 +13:00

39 lines
887 B
Rust

use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn try_succeed() {
Playground::setup("try_succeed_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
"try { 345 } catch { echo 'hello' }"
);
assert!(output.out.contains("345"));
})
}
#[test]
fn try_catch() {
Playground::setup("try_catch_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
"try { foobarbaz } catch { echo 'hello' }"
);
assert!(output.out.contains("hello"));
})
}
#[test]
fn catch_can_access_error() {
Playground::setup("try_catch_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
"try { foobarbaz } catch { |err| $err }"
);
assert!(output.err.contains("External command failed"));
})
}