001/*
002 * JDrupes Builder
003 * Copyright (C) 2025, 2026 Michael N. Lipp
004 * 
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
017 */
018
019package org.jdrupes.builder.api;
020
021import java.util.Optional;
022
023/// Represents an exception that occurs during the build. Terminates the
024/// current build when thrown.
025///
026@SuppressWarnings("serial")
027public class BuildException extends RuntimeException {
028
029    private ResourceProvider resourceProvider;
030
031    /// Initializes a new builds the exception.
032    ///
033    public BuildException() {
034        super();
035    }
036
037    /// Instantiates a new build exception. As a convenience, any
038    /// Throwable arguments will be replaced by their message.
039    ///
040    /// @param format the format
041    /// @param args the args
042    ///
043    public BuildException(String format, Object... args) {
044        for (int i = 0; i < args.length; i++) {
045            if (args[i] instanceof Throwable) {
046                args[i] = ((Throwable) args[i]).getMessage();
047            }
048        }
049        var message = String.format(format, args);
050        super(message);
051    }
052
053    /// Sets the cause.
054    ///
055    /// @param cause the cause
056    /// @return the builds the exception
057    ///
058    public BuildException cause(Throwable cause) {
059        initCause(cause);
060        return this;
061    }
062
063    /// From.
064    ///
065    /// @param resourceProvider the resource provider
066    /// @return the builds the exception
067    ///
068    public BuildException from(ResourceProvider resourceProvider) {
069        this.resourceProvider = resourceProvider;
070        return this;
071    }
072
073    /// Returns the origin of this exception. This is the resource
074    /// provider set with [#from].
075    ///
076    /// @return the resource provider
077    ///
078    public Optional<ResourceProvider> origin() {
079        return Optional.ofNullable(resourceProvider);
080    }
081}