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 * http://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 */ 017package org.apache.juneau.internal; 018 019import static org.apache.juneau.common.utils.StringUtils.*; 020import static org.apache.juneau.common.utils.ThrowableUtils.*; 021 022/** 023 * Builder class for {@link Exception} objects. 024 * 025 * <h5 class='section'>See Also:</h5><ul> 026 * </ul> 027 * 028 * @param <T> The exception class. 029 */ 030public class ExceptionBuilder<T extends Throwable> { 031 032 private final Class<T> type; 033 private String message; 034 private Throwable causedBy; 035 036 /** 037 * Default constructor. 038 * @param type The exception type to create. 039 */ 040 public ExceptionBuilder(Class<T> type) { 041 this.type = type; 042 } 043 044 /** 045 * Specifies the exception message. 046 * 047 * @param msg The exception message. Can be <jk>null</jk>. 048 * <br>If <jk>null</jk>, then the caused-by message is used if available. 049 * @param args The exception message arguments. 050 * @return This object. 051 */ 052 public ExceptionBuilder<T> message(String msg, Object...args) { 053 message = format(msg, args); 054 return this; 055 } 056 057 /** 058 * Specifies the caused-by exception. 059 * 060 * @param value The caused-by exception. Can be <jk>null</jk>. 061 * @return This object. 062 */ 063 public ExceptionBuilder<T> causedBy(Throwable value) { 064 causedBy = value; 065 return this; 066 } 067 /** 068 * Creates the exception. 069 * 070 * @return The exception. 071 */ 072 public T build() { 073 try { 074 return type.getConstructor(String.class, Throwable.class).newInstance(message, causedBy); 075 } catch (Exception e) { 076 throw asRuntimeException(e); 077 } 078 } 079}