ConfigException.java

/*
 * Copyright 2023 Morimekta Utils Authors
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.config;

import java.util.Arrays;

/**
 * Exception related to config handling and loading.
 */
public class ConfigException extends Exception {
    /**
     * @param message Exception message.
     */
    public ConfigException(String message) {
        super(String.valueOf(message));
    }

    /**
     * @param message Exception message.
     * @param cause   Cause of exception.
     */
    public ConfigException(String message, Throwable cause) {
        super(String.valueOf(message), cause);
    }

    /**
     * @return An unchecked version of the exception.
     */
    public UncheckedConfigException asUncheckedException() {
        return new UncheckedConfigException(this);
    }

    /**
     * Make a config exception out of an exception. If it's already a config
     * exception will just pass the exception.
     *
     * @param e The exception to possibly wrap.
     * @return The config exception.
     */
    public static ConfigException asConfigException(Throwable e) {
        return asConfigException(e, 2);
    }

    /**
     * Make a config exception out of an exception. If it's already a config
     * exception will just pass the exception.
     *
     * @param e              The exception to possibly wrap.
     * @param skipTopOfStack Number of entries to skip at top of stack trace,
     *                       including this method.
     * @return The config exception.
     */
    public static ConfigException asConfigException(Throwable e, int skipTopOfStack) {
        if (e instanceof ConfigException) {
            return (ConfigException) e;
        }
        var out = new ConfigException(e.getMessage(), e);
        if (0 < skipTopOfStack) {
            var trace = out.getStackTrace();
            if (skipTopOfStack < trace.length) {
                out.setStackTrace(Arrays.copyOfRange(trace, skipTopOfStack, trace.length));
            }
        }
        return out;
    }
}