blob: 36b74dda8cc07e74dd6757a0af2d526c02f5302d [file] [log] [blame]
limpbizkitb1d8ab42008-04-27 08:11:37 +00001/**
2 * Copyright (C) 2008 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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 */
16
17
18package com.google.inject;
19
limpbizkit64c7bfa2008-04-27 08:16:37 +000020import com.google.inject.internal.ErrorHandler;
21import com.google.inject.internal.ErrorMessages;
limpbizkitb1d8ab42008-04-27 08:11:37 +000022import com.google.inject.spi.Message;
23
limpbizkitb1d8ab42008-04-27 08:11:37 +000024import java.util.ArrayList;
limpbizkit64c7bfa2008-04-27 08:16:37 +000025import java.util.Collection;
limpbizkitb1d8ab42008-04-27 08:11:37 +000026
27/**
28 * A stateful error handler that can be used at both configuration time and
29 * at runtime. By using the same error handler in both situations, a reference
30 * to this error handler will work in both situations.
31 *
32 * @author crazybob@google.com (Bob Lee)
33 * @author jessewilson@google.com (Jesse Wilson)
34 */
limpbizkit64c7bfa2008-04-27 08:16:37 +000035class DefaultErrorHandler implements ErrorHandler {
limpbizkitb1d8ab42008-04-27 08:11:37 +000036 State state = State.CONFIGURATION_TIME;
37 final Collection<Message> errorMessages = new ArrayList<Message>();
38
39 public void handle(Object source, String message) {
limpbizkit3b1cd582008-04-28 00:06:01 +000040 source = ErrorMessages.convert(source);
41
limpbizkitb1d8ab42008-04-27 08:11:37 +000042 if (state == State.RUNTIME) {
43 throw new ConfigurationException("Error at " + source + " " + message);
44
45 } else if (state == State.CONFIGURATION_TIME) {
46 errorMessages.add(new Message(source, message));
47
48 } else {
49 throw new AssertionError();
50 }
51 }
52
limpbizkit64c7bfa2008-04-27 08:16:37 +000053 /**
54 * Implements formatting. Converts known types to readable strings.
55 */
56 public final void handle(Object source, String message, Object... arguments) {
limpbizkit3b1cd582008-04-28 00:06:01 +000057 handle(source, ErrorMessages.format(message, arguments));
limpbizkit64c7bfa2008-04-27 08:16:37 +000058 }
59
limpbizkitb1d8ab42008-04-27 08:11:37 +000060 void blowUpIfErrorsExist() {
61 if (!errorMessages.isEmpty()) {
62 throw new CreationException(errorMessages);
63 }
64 }
65
limpbizkitf5b13b32008-04-27 08:59:10 +000066 void switchToRuntime() {
67 state = State.RUNTIME;
68 errorMessages.clear();
69 }
70
limpbizkitb1d8ab42008-04-27 08:11:37 +000071 enum State {
72 CONFIGURATION_TIME, RUNTIME
73 }
74}