01: /**
02: * Copyright (C) 2006, 2007 David Bulmore, Software Sensation Inc.
03: * All Rights Reserved.
04: *
05: * This file is part of jCommonTk.
06: *
07: * jCommonTk is free software; you can redistribute it and/or modify it under
08: * the terms of the GNU General Public License (Version 2) as published by
09: * the Free Software Foundation.
10: *
11: * jCommonTk is distributed in the hope that it will be useful, but WITHOUT
12: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14: * for more details.
15: *
16: * You should have received a copy of the GNU General Public License
17: * along with jCommonTk; if not, write to the Free Software Foundation,
18: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19: */package jcommontk.utils;
20:
21: public class ExceptionUtils {
22: public static String normalizeMessage(Exception e) {
23: return normalizeMessage(e, false);
24: }
25:
26: public static String normalizeMessage(Exception e,
27: boolean useHtmlBreak) {
28: String message = "";
29: Throwable t = e;
30:
31: do {
32: if (message.length() > 0) {
33: message += useHtmlBreak ? "<br>" : "\n";
34: message += "Caused by: "
35: + (useHtmlBreak ? "<br>" : "\n");
36: message += " " + t;
37: } else
38: message += t;
39: } while ((t = t.getCause()) != null);
40:
41: if (useHtmlBreak)
42: message = message.replaceAll("\n", "<br>");
43:
44: return message;
45: }
46:
47: public static String firstMessage(Exception e) {
48: String message = null;
49: Throwable t = e;
50:
51: while ((t = t.getCause()) != null)
52: message = t.getMessage();
53:
54: return message;
55: }
56:
57: public static class JCommonException extends Exception {
58: private static final long serialVersionUID = 100L;
59:
60: public JCommonException(Throwable cause) {
61: super (getBetterMessage(cause, cause.getMessage()), cause);
62:
63: if (cause instanceof RuntimeException)
64: throw (RuntimeException) cause;
65: }
66:
67: public JCommonException(String message) {
68: super (message);
69: }
70:
71: public JCommonException(String message, Throwable cause) {
72: super (getBetterMessage(cause, message), cause);
73:
74: if (cause instanceof RuntimeException)
75: throw (RuntimeException) cause;
76: }
77: }
78:
79: public static String getBetterMessage(Throwable t, String message) {
80: if (t instanceof IllegalAccessException)
81: return "IllegalAccessException - Can't access member due to visibility (non-public)";
82: else if (t instanceof InstantiationException)
83: return "InstantiationException - Can't create new instance because of visibility (not public), or there's no suitable\n"
84: + "constructor (might need an empty constructor), or it's an interface, or it's an abstract class";
85:
86: return message;
87: }
88: }
|