nu_cmd_lang/core_commands/
try_.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::engine::CommandType;
3
4#[derive(Clone)]
5pub struct Try;
6
7impl Command for Try {
8    fn name(&self) -> &str {
9        "try"
10    }
11
12    fn description(&self) -> &str {
13        "Try to run a block, if it fails optionally run a catch closure."
14    }
15
16    fn signature(&self) -> nu_protocol::Signature {
17        Signature::build("try")
18            .input_output_types(vec![(Type::Any, Type::Any)])
19            .required("try_block", SyntaxShape::Block, "Block to run.")
20            .optional(
21                "catch_closure",
22                SyntaxShape::Keyword(
23                    b"catch".to_vec(),
24                    Box::new(SyntaxShape::OneOf(vec![
25                        SyntaxShape::Closure(None),
26                        SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
27                    ])),
28                ),
29                "Closure to run if try block fails.",
30            )
31            .category(Category::Core)
32    }
33
34    fn extra_description(&self) -> &str {
35        r#"This command is a parser keyword. For details, check:
36  https://www.nushell.sh/book/thinking_in_nu.html"#
37    }
38
39    fn command_type(&self) -> CommandType {
40        CommandType::Keyword
41    }
42
43    fn run(
44        &self,
45        _engine_state: &EngineState,
46        _stack: &mut Stack,
47        _call: &Call,
48        _input: PipelineData,
49    ) -> Result<PipelineData, ShellError> {
50        // This is compiled specially by the IR compiler. The code here is never used when
51        // running in IR mode.
52        eprintln!(
53            "Tried to execute 'run' for the 'try' command: this code path should never be reached in IR mode"
54        );
55        unreachable!();
56    }
57
58    fn examples(&self) -> Vec<Example<'_>> {
59        vec![
60            Example {
61                description: "Try to run a division by zero",
62                example: "try { 1 / 0 }",
63                result: None,
64            },
65            Example {
66                description: "Try to run a division by zero and return a string instead",
67                example: "try { 1 / 0 } catch { 'divided by zero' }",
68                result: Some(Value::test_string("divided by zero")),
69            },
70            Example {
71                description: "Try to run a division by zero and report the message",
72                example: "try { 1 / 0 } catch { |err| $err.msg }",
73                result: None,
74            },
75        ]
76    }
77}
78
79#[cfg(test)]
80mod test {
81    use super::*;
82
83    #[test]
84    fn test_examples() {
85        use crate::test_examples;
86
87        test_examples(Try {})
88    }
89}