001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
002//
003// SPDX-License-Identifier: Apache-2.0
004
005package sop.cli.picocli;
006
007import picocli.CommandLine;
008
009public class SOPExecutionExceptionHandler implements CommandLine.IExecutionExceptionHandler {
010
011    @Override
012    public int handleExecutionException(Exception ex, CommandLine commandLine, CommandLine.ParseResult parseResult) {
013        int exitCode = commandLine.getExitCodeExceptionMapper() != null ?
014                commandLine.getExitCodeExceptionMapper().getExitCode(ex) :
015                commandLine.getCommandSpec().exitCodeOnExecutionException();
016        CommandLine.Help.ColorScheme colorScheme = commandLine.getColorScheme();
017        // CHECKSTYLE:OFF
018        if (ex.getMessage() != null) {
019            commandLine.getErr().println(colorScheme.errorText(ex.getMessage()));
020        }
021        ex.printStackTrace(commandLine.getErr());
022        // CHECKSTYLE:ON
023
024        return exitCode;
025    }
026}