1 /*
2  * Copyright 2018 The Android Open Source Project
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 package androidx.appsearch.compiler;
17 
18 import androidx.annotation.RestrictTo;
19 
20 import org.jspecify.annotations.NonNull;
21 import org.jspecify.annotations.Nullable;
22 
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.List;
26 
27 import javax.annotation.processing.Messager;
28 import javax.lang.model.element.Element;
29 import javax.tools.Diagnostic;
30 
31 /**
32  * An exception thrown from the appsearch annotation processor to indicate something went wrong.
33  * @exportToFramework:hide
34  */
35 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
36 public final class ProcessingException extends Exception {
37     private final @Nullable Element mCulprit;
38 
39     /**
40      * Warnings associated with this error which should be reported alongside it at a lower level.
41      */
42     private final List<ProcessingException> mWarnings = new ArrayList<>();
43 
ProcessingException(@onNull String message, @Nullable Element culprit)44     public ProcessingException(@NonNull String message, @Nullable Element culprit) {
45         super(message);
46         mCulprit = culprit;
47     }
48 
addWarning(@onNull ProcessingException warning)49     public void addWarning(@NonNull ProcessingException warning) {
50         mWarnings.add(warning);
51     }
52 
addWarnings(@onNull Collection<ProcessingException> warnings)53     public void addWarnings(@NonNull Collection<ProcessingException> warnings) {
54         mWarnings.addAll(warnings);
55     }
56 
printDiagnostic(Messager messager)57     public void printDiagnostic(Messager messager) {
58         printDiagnostic(messager, Diagnostic.Kind.ERROR);
59     }
60 
printDiagnostic(Messager messager, Diagnostic.Kind level)61     private void printDiagnostic(Messager messager, Diagnostic.Kind level) {
62         messager.printMessage(level, getMessage(), mCulprit);
63         for (ProcessingException warning : mWarnings) {
64             warning.printDiagnostic(messager, Diagnostic.Kind.WARNING);
65         }
66     }
67 }
68