01: /**
02: * Copyright (C) 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */package com.google.inject;
16:
17: import com.google.inject.spi.Message;
18: import java.util.ArrayList;
19: import java.util.Collection;
20: import java.util.Collections;
21: import java.util.Comparator;
22: import java.util.Formatter;
23: import java.util.List;
24:
25: /**
26: * Thrown when errors occur while creating a {@link Injector}. Includes a list
27: * of encountered errors. Typically, a client should catch this exception, log
28: * it, and stop execution.
29: *
30: * @author crazybob@google.com (Bob Lee)
31: */
32: public class CreationException extends RuntimeException {
33:
34: final List<Message> errorMessages;
35:
36: /**
37: * Constructs a new exception for the given errors.
38: */
39: public CreationException(Collection<Message> errorMessages) {
40: super ();
41:
42: // Sort the messages by source.
43: this .errorMessages = new ArrayList<Message>(errorMessages);
44: Collections.sort(this .errorMessages, new Comparator<Message>() {
45: public int compare(Message a, Message b) {
46: return a.getSourceString().compareTo(
47: b.getSourceString());
48: }
49: });
50: }
51:
52: public String getMessage() {
53: return createErrorMessage(errorMessages);
54: }
55:
56: private static String createErrorMessage(
57: Collection<Message> errorMessages) {
58: Formatter fmt = new Formatter()
59: .format("Guice configuration errors:%n%n");
60: int index = 1;
61: for (Message errorMessage : errorMessages) {
62: fmt.format("%s) Error at %s:%n", index++,
63: errorMessage.getSourceString()).format(" %s%n%n",
64: errorMessage.getMessage());
65: }
66: return fmt.format("%s error[s]", errorMessages.size())
67: .toString();
68: }
69:
70: /**
71: * Gets the error messages which resulted in this exception.
72: */
73: public Collection<Message> getErrorMessages() {
74: return Collections.unmodifiableCollection(errorMessages);
75: }
76: }
|