Here you can find the source of stackTraceToString(Throwable t)
Parameter | Description |
---|---|
t | exception to print |
public static String stackTraceToString(Throwable t)
//package com.java2s; /******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * /*from ww w. jav a 2 s.c om*/ * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *******************************************************************************/ import java.io.PrintWriter; import java.io.StringWriter; public class Main { private static final int MAX_CHARS = 20000; private static final boolean PRINT_STACK_TRACE = true; /** * Print exception stack trace to string if allowed. * * @param t exception to print * @return string with exception or null if stack trace printing disabled */ public static String stackTraceToString(Throwable t) { if (PRINT_STACK_TRACE) { StringWriter descr = new StringWriter() { boolean writeOK = true; public void write(char[] cbuf, int off, int len) { if (canWrite()) super.write(cbuf, off, len); } public void write(int c) { if (canWrite()) super.write(c); } public void write(String str, int off, int len) { if (canWrite()) super.write(str, off, len); } public void write(String str) { if (canWrite()) super.write(str); } private boolean canWrite() { if (writeOK && this.getBuffer().length() > MAX_CHARS) { super.write(" ... [ too long - truncated ]"); //$NON-NLS-1$ writeOK = false; } return writeOK; } }; t.printStackTrace(new PrintWriter(descr)); return descr.toString(); } else { return null; } } /** * Converts throwable to string. * * @param t the throwable to be converted * @return string serialization of the throwable */ public static String toString(Throwable t) { String s = stackTraceToString(t); if (s == null) s = "Exception " + t.getClass().getName() + " : " + t.getMessage(); //$NON-NLS-1$ //$NON-NLS-2$ return s; } }