001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.internal; 014 015import static org.apache.juneau.common.internal.StringUtils.*; 016import static org.apache.juneau.common.internal.ThrowableUtils.*; 017 018/** 019 * Builder class for {@link Exception} objects. 020 * 021 * <h5 class='section'>See Also:</h5><ul> 022 * </ul> 023 * 024 * @param <T> The exception class. 025 */ 026@FluentSetters 027public class ExceptionBuilder<T extends Throwable> { 028 029 private final Class<T> type; 030 private String message; 031 private Throwable causedBy; 032 033 /** 034 * Default constructor. 035 * @param type The exception type to create. 036 */ 037 public ExceptionBuilder(Class<T> type) { 038 this.type = type; 039 } 040 041 /** 042 * Specifies the exception message. 043 * 044 * @param msg The exception message. Can be <jk>null</jk>. 045 * <br>If <jk>null</jk>, then the caused-by message is used if available. 046 * @param args The exception message arguments. 047 * @return This object. 048 */ 049 @FluentSetter 050 public ExceptionBuilder<T> message(String msg, Object...args) { 051 message = format(msg, args); 052 return this; 053 } 054 055 /** 056 * Specifies the caused-by exception. 057 * 058 * @param value The caused-by exception. Can be <jk>null</jk>. 059 * @return This object. 060 */ 061 @FluentSetter 062 public ExceptionBuilder<T> causedBy(Throwable value) { 063 causedBy = value; 064 return this; 065 } 066 067 // <FluentSetters> 068 069 // </FluentSetters> 070 071 /** 072 * Creates the exception. 073 * 074 * @return The exception. 075 */ 076 public T build() { 077 try { 078 return type.getConstructor(String.class, Throwable.class).newInstance(message, causedBy); 079 } catch (Exception e) { 080 throw asRuntimeException(e); 081 } 082 } 083}