package com.atlassian.bitbucket.mesh.boot;

import com.atlassian.bitbucket.mesh.app.ApplicationStartupException;
import org.springframework.boot.diagnostics.FailureAnalysis;
import org.springframework.boot.diagnostics.FailureAnalyzer;

/**
 * Spring Boot {@link FailureAnalyzer} for exceptions intended to prevent application startup. This ensures that
 * administrators get a helpful error message with instructions on how to correct the problem.
 *
 * @see ApplicationStartupException
 * @see com.atlassian.bitbucket.mesh.app.IllegalApplicationStateException
 */
public class StartupFailureAnalyzer implements FailureAnalyzer {

    @Override
    public FailureAnalysis analyze(Throwable failure) {
        Throwable cause = failure;
        while (cause != null) {
            if (cause instanceof ApplicationStartupException) {
                return new FailureAnalysis(cause.getMessage(), ((ApplicationStartupException) cause).getAction(), cause);
            }
            cause = cause.getCause();
        }

        return null;
    }
}
