Blog-Archiv

Montag, 20. Juli 2020

Format Java Stack Trace without Newlines

There seem to be situations where a stack trace loses its newlines. That's annoying, because I recently searched for an online tool that facilitates restoring them, but didn't find one. Some actually added newlines, but not at "Caused by: ", which you find with nested exceptions. Now here is my ....

Formatter

.... which formats stack traces that lost their newlines.

Stack Trace Input









Formatted Output

When you paste (Ctrl-V) your stack trace line in the left text area and then press "Format", you will hopefully see a beautiful stack trace on the right side.

Mind that the stack trace line still needs to have tabs ('\t', 9). When not, try to activate the "Tab is Space" checkbox.

For the interested, here is the JavaScript that does this (click to expand).
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/** 
 * @param NEWLINE = "WINDOWS" or "MacOS" or "UNIX".
 * @param tabIsSpace true when tabs have been lost in stack trace line.
 */
var stackTraceFormatter = function(NEWLINE, tabIsSpace) {
    NEWLINE = (NEWLINE === "WINDOWS") ? "\r\n" : (NEWLINE === "MacOS") ? "\r" : "\n";
    var TAB = "\t";
    var SEPARATOR = tabIsSpace ? " at " : TAB;
    
    var NEWLINE_WITH_TAB = tabIsSpace ? NEWLINE+TAB+"at " : NEWLINE+TAB;
    var CAUSED_BY = "Caused by: ";
    var NEWLINE_WITH_CAUSED_BY = NEWLINE+CAUSED_BY;
    
    var startsWith = function(text, searchString) {
        return text.substr(0, searchString.length) === searchString;
    };
    
    var that = {};
    
    that.format = function(stackTrace) {
        if (startsWith(stackTrace, SEPARATOR) === false)
          stackTrace = stackTrace.trim();
        
        if (stackTrace.indexOf('\n') >= 0 || stackTrace.indexOf('\r') >= 0)
          return stackTrace;
        
        var s1 = stackTrace.split(SEPARATOR).join(NEWLINE_WITH_TAB);
        var s2 = s1.split(CAUSED_BY).join(NEWLINE_WITH_CAUSED_BY);
        
        return tabIsSpace ? s2.split(" ... ").join(NEWLINE+TAB+"... ") : s2;
    };
    
    return that;
};

  var text = ....;
  var formatter = stackTraceFormatter("UNIX", false);
  var stackTrace = formatter.format(text);



Keine Kommentare: