001/*
002 * SPDX-FileCopyrightText: none
003 * SPDX-License-Identifier: CC0-1.0
004 */
005
006package gov.nist.secauto.metaschema.cli.processor.command;
007
008import gov.nist.secauto.metaschema.cli.processor.ExitCode;
009import gov.nist.secauto.metaschema.cli.processor.ExitStatus;
010
011import edu.umd.cs.findbugs.annotations.NonNull;
012
013/**
014 * For use in commands to short-circut command execution.
015 */
016public class CommandExecutionException
017    extends Exception {
018  private final ExitCode exitCode;
019
020  /**
021   * the serial version UID.
022   */
023  private static final long serialVersionUID = 1L;
024
025  /**
026   * Constructs a new exception with the provided {@code code}, and no message or
027   * cause.
028   *
029   * @param code
030   *          the exit code associated with this error
031   */
032  public CommandExecutionException(@NonNull ExitCode code) {
033    this.exitCode = code;
034  }
035
036  /**
037   * Constructs a new exception with the provided {@code code}, {@code message},
038   * and no cause.
039   *
040   * @param code
041   *          the exit code associated with this error
042   * @param message
043   *          the exception message
044   */
045  public CommandExecutionException(@NonNull ExitCode code, String message) {
046    super(message);
047    this.exitCode = code;
048  }
049
050  /**
051   * Constructs a new exception with no message and the provided {@code code} and
052   * {@code cause}.
053   *
054   * @param code
055   *          the exit code associated with this error
056   * @param cause
057   *          the original exception cause
058   */
059  public CommandExecutionException(@NonNull ExitCode code, Throwable cause) {
060    super(cause);
061    this.exitCode = code;
062  }
063
064  /**
065   * Constructs a new exception with the provided {@code code}, {@code message},
066   * and {@code cause}.
067   *
068   * @param code
069   *          the exit code associated with this error
070   * @param message
071   *          the exception message
072   * @param cause
073   *          the original exception cause
074   */
075  public CommandExecutionException(@NonNull ExitCode code, String message, Throwable cause) {
076    super(message, cause);
077    this.exitCode = code;
078  }
079
080  /**
081   * Generate an {@link ExitStatus} based on this exception.
082   *
083   * @return the exit status
084   */
085  @NonNull
086  public ExitStatus toExitStatus() {
087    String message = getLocalizedMessage();
088
089    ExitStatus retval = message == null
090        ? exitCode.exit()
091        : exitCode.exitMessage(message);
092
093    Throwable cause = getCause();
094    if (cause != null) {
095      retval.withThrowable(cause);
096    }
097    return retval;
098  }
099}