001/*
002 * Copyright 2023 the original author or authors.
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * https://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package de.cuioss.test.valueobjects.objects.impl;
017
018import java.lang.reflect.InvocationTargetException;
019
020import lombok.experimental.UtilityClass;
021
022/**
023 * Helper class used for accessing an exception message in a general way
024 *
025 * @author Oliver Wolff
026 */
027@UtilityClass
028public final class ExceptionHelper {
029
030    private static final String NO_MESSAGE = "No exception message could be extracted";
031
032    /**
033     * Extracts a message from a given throwable in a safe manner. It specially
034     * handles {@link InvocationTargetException}
035     *
036     * @param throwable
037     * @return the extract message;
038     */
039    public static String extractMessageFromThrowable(final Throwable throwable) {
040        if (null == throwable) {
041            return NO_MESSAGE;
042        }
043        return throwable.getClass().getSimpleName() + " " + throwable.getMessage();
044    }
045
046    /**
047     * Extracts a message from a given throwable in a safe manner. It specially
048     * handles {@link InvocationTargetException}
049     *
050     * @param throwable
051     * @return the extract message;
052     */
053    public static String extractCauseMessageFromThrowable(final Throwable throwable) {
054        if (null == throwable) {
055            return NO_MESSAGE;
056        }
057        if (throwable instanceof InvocationTargetException exception) {
058            return extractMessageFromThrowable(exception.getTargetException());
059        }
060        return extractMessageFromThrowable(throwable);
061    }
062}