package com.atlassian.bitbucket.mesh;

import io.grpc.Metadata;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static java.util.Objects.requireNonNull;

public class AbstractStatusException extends RuntimeException {

    private final Status status;

    public AbstractStatusException(@Nullable String message, @Nonnull Status status) {
        super(message);

        this.status = requireNonNull(status, "status");
    }

    public AbstractStatusException(@Nullable String message, @Nullable Throwable cause, @Nonnull Status status) {
        super(message, cause);

        this.status = requireNonNull(status, "status");
    }

    public AbstractStatusException(@Nullable Throwable cause, @Nonnull Status status) {
        super(cause);

        this.status = requireNonNull(status, "status");
    }

    @Nonnull
    public Status getStatus() {
        return status;
    }

    @Nonnull
    public StatusRuntimeException toStatusException() {
        return getStatus()
                .withCause(this)
                .withDescription(getMessage())
                .asRuntimeException(getTrailers());
    }

    @Nullable
    protected Metadata getTrailers() {
        return null;
    }
}
