    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.io;
    019
    020import java.io.IOException;
    021
    022/**
    023 * A IOException associated with a source index.
    024 *
    025 * @since 2.7
    026 */
    027public class IOIndexedException extends IOException {
    028
    029    private static final long serialVersionUID = 1L;
    030
    031    /**
    032     * Converts input to a suitable String for exception message.
    033     *
    034     * @param index An index into a source collection.
    035     * @param cause A cause.
    036     * @return A message.
    037     */
    038    protected static String toMessage(final int index, final Throwable cause) {
    039        // Letting index be any int
    040        final String unspecified = "Null";
    041        final String name = cause == null ? unspecified : cause.getClass().getSimpleName();
    042        final String msg = cause == null ? unspecified : cause.getMessage();
    043        return String.format("%s #%,d: %s", name, index, msg);
    044    }
    045
    046    /**
    047     * Index.
    048     */
    049    private final int index;
    050
    051    /**
    052     * Constructs a new exception.
    053     *
    054     * @param index index of this exception.
    055     * @param cause cause exceptions.
    056     */
    057    public IOIndexedException(final int index, final Throwable cause) {
    058        super(toMessage(index, cause), cause);
    059        this.index = index;
    060    }
    061
    062    /**
    063     * The index of this exception.
    064     *
    065     * @return index of this exception.
    066     */
    067    public int getIndex() {
    068        return index;
    069    }
    070
    071}