1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package dev.metaschema.cli.processor.command;
7   
8   import dev.metaschema.cli.processor.ExitCode;
9   import dev.metaschema.cli.processor.ExitStatus;
10  import edu.umd.cs.findbugs.annotations.NonNull;
11  
12  /**
13   * For use in commands to short-circut command execution.
14   */
15  public class CommandExecutionException
16      extends Exception {
17    /**
18     * The exit code indicating the type of error that occurred.
19     */
20    private final ExitCode exitCode;
21  
22    /**
23     * the serial version UID.
24     */
25    private static final long serialVersionUID = 1L;
26  
27    /**
28     * Constructs a new exception with the provided {@code code}, and no message or
29     * cause.
30     *
31     * @param code
32     *          the exit code associated with this error
33     */
34    public CommandExecutionException(@NonNull ExitCode code) {
35      this.exitCode = code;
36    }
37  
38    /**
39     * Constructs a new exception with the provided {@code code}, {@code message},
40     * and no cause.
41     *
42     * @param code
43     *          the exit code associated with this error
44     * @param message
45     *          the exception message
46     */
47    public CommandExecutionException(@NonNull ExitCode code, String message) {
48      super(message);
49      this.exitCode = code;
50    }
51  
52    /**
53     * Constructs a new exception with no message and the provided {@code code} and
54     * {@code cause}.
55     *
56     * @param code
57     *          the exit code associated with this error
58     * @param cause
59     *          the original exception cause
60     */
61    public CommandExecutionException(@NonNull ExitCode code, Throwable cause) {
62      super(cause);
63      this.exitCode = code;
64    }
65  
66    /**
67     * Constructs a new exception with the provided {@code code}, {@code message},
68     * and {@code cause}.
69     *
70     * @param code
71     *          the exit code associated with this error
72     * @param message
73     *          the exception message
74     * @param cause
75     *          the original exception cause
76     */
77    public CommandExecutionException(@NonNull ExitCode code, String message, Throwable cause) {
78      super(message, cause);
79      this.exitCode = code;
80    }
81  
82    /**
83     * Generate an {@link ExitStatus} based on this exception.
84     *
85     * @return the exit status
86     */
87    @NonNull
88    public ExitStatus toExitStatus() {
89      String message = getLocalizedMessage();
90  
91      ExitStatus retval = message == null
92          ? exitCode.exit()
93          : exitCode.exitMessage(message);
94  
95      Throwable cause = getCause();
96      if (cause != null) {
97        retval.withThrowable(cause);
98      }
99      return retval;
100   }
101 }