/*
 * 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 org.apache.kafka.streams.errors;

import org.apache.kafka.common.KafkaException;
import org.apache.kafka.streams.processor.TaskId;

import java.util.Optional;

/**
 * {@link StreamsException} is the top-level exception type generated by Kafka Streams, and indicates errors have
 * occurred during a {@link org.apache.kafka.streams.processor.internals.StreamThread StreamThread's} processing. It
 * is guaranteed that any exception thrown up to the {@link StreamsUncaughtExceptionHandler} will be of the type
 * {@code StreamsException}. For example, any user exceptions will be wrapped as a {@code StreamsException}.
 */
public class StreamsException extends KafkaException {

    private final static long serialVersionUID = 1L;

    private TaskId taskId;

    public StreamsException(final String message) {
        this(message, (TaskId) null);
    }

    public StreamsException(final String message, final TaskId taskId) {
        super(message);
        this.taskId = taskId;
    }

    public StreamsException(final String message, final Throwable throwable) {
        this(message, throwable, null);
    }

    public StreamsException(final String message, final Throwable throwable, final TaskId taskId) {
        super(message, throwable);
        this.taskId = taskId;
    }

    public StreamsException(final Throwable throwable) {
        this(throwable, null);
    }

    public StreamsException(final Throwable throwable, final TaskId taskId) {
        super(throwable);
        this.taskId = taskId;
    }

    /**
     * @return  the {@link TaskId} that this exception originated from, or {@link Optional#empty()} if the exception
     *          cannot be traced back to a particular task. Note that the {@code TaskId} being empty does not
     *          guarantee that the exception wasn't directly related to a specific task.
     */
    public Optional<TaskId> taskId() {
        return Optional.ofNullable(taskId);
    }

    public void setTaskId(final TaskId taskId) {
        this.taskId = taskId;
    }
}
