1/*
2 * Copyright (C) 2014 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
17package android.util;
18
19import java.io.IOException;
20
21/**
22 * Utility methods for proxying richer exceptions across Binder calls.
23 *
24 * @hide
25 */
26public class ExceptionUtils {
27    // TODO: longer term these should be replaced with first-class
28    // Parcel.read/writeException() and AIDL support, but for now do this using
29    // a nasty hack.
30
31    private static final String PREFIX_IO = "\u2603";
32
33    public static RuntimeException wrap(IOException e) {
34        throw new IllegalStateException(PREFIX_IO + e.getMessage());
35    }
36
37    public static void maybeUnwrapIOException(RuntimeException e) throws IOException {
38        if ((e instanceof IllegalStateException) && e.getMessage().startsWith(PREFIX_IO)) {
39            throw new IOException(e.getMessage().substring(PREFIX_IO.length()));
40        }
41    }
42
43    public static String getCompleteMessage(String msg, Throwable t) {
44        final StringBuilder builder = new StringBuilder();
45        if (msg != null) {
46            builder.append(msg).append(": ");
47        }
48        builder.append(t.getMessage());
49        while ((t = t.getCause()) != null) {
50            builder.append(": ").append(t.getMessage());
51        }
52        return builder.toString();
53    }
54
55    public static String getCompleteMessage(Throwable t) {
56        return getCompleteMessage(null, t);
57    }
58}
59