1 /*
   2  * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code 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  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.nashorn.api.scripting;
  27 
  28 import java.util.ArrayList;
  29 import java.util.List;
  30 import jdk.nashorn.internal.codegen.CompilerConstants;
  31 import jdk.nashorn.internal.runtime.ECMAErrors;
  32 
  33 /**
  34  * This is base exception for all Nashorn exceptions. These originate from
  35  * user's ECMAScript code. Example: script parse errors, exceptions thrown from
  36  * scripts. Note that ScriptEngine methods like "eval", "invokeMethod",
  37  * "invokeFunction" will wrap this as ScriptException and throw it. But, there
  38  * are cases where user may need to access this exception (or implementation
  39  * defined subtype of this). For example, if java interface is implemented by a
  40  * script object or Java access to script object properties via java.util.Map
  41  * interface. In these cases, user code will get an instance of this or
  42  * implementation defined subclass.
  43  */
  44 @SuppressWarnings("serial")
  45 public abstract class NashornException extends RuntimeException {
  46     // script file name
  47     private final String fileName;
  48     // script line number
  49     private final int line;
  50     // script column number
  51     private final int column;
  52 
  53     /** script source name used for "engine.js" */
  54     public static final String ENGINE_SCRIPT_SOURCE_NAME = "nashorn:engine/resources/engine.js";
  55 
  56     /**
  57      * Constructor
  58      *
  59      * @param msg       exception message
  60      * @param fileName  file name
  61      * @param line      line number
  62      * @param column    column number
  63      */
  64     protected NashornException(final String msg, final String fileName, final int line, final int column) {
  65         this(msg, null, fileName, line, column);
  66     }
  67 
  68     /**
  69      * Constructor
  70      *
  71      * @param msg       exception message
  72      * @param cause     exception cause
  73      * @param fileName  file name
  74      * @param line      line number
  75      * @param column    column number
  76      */
  77     protected NashornException(final String msg, final Throwable cause, final String fileName, final int line, final int column) {
  78         super(msg, cause == null ? null : cause);
  79         this.fileName = fileName;
  80         this.line = line;
  81         this.column = column;
  82     }
  83 
  84     /**
  85      * Constructor
  86      *
  87      * @param msg       exception message
  88      * @param cause     exception cause
  89      */
  90     protected NashornException(final String msg, final Throwable cause) {
  91         super(msg, cause == null ? null : cause);
  92         // This is not so pretty - but it gets the job done. Note that the stack
  93         // trace has been already filled by "fillInStackTrace" call from
  94         // Throwable
  95         // constructor and so we don't pay additional cost for it.
  96 
  97         // Hard luck - no column number info
  98         this.column = -1;
  99 
 100         // Find the first JavaScript frame by walking and set file, line from it
 101         // Usually, we should be able to find it in just few frames depth.
 102         for (final StackTraceElement ste : getStackTrace()) {
 103             if (ECMAErrors.isScriptFrame(ste)) {
 104                 // Whatever here is compiled from JavaScript code
 105                 this.fileName = ste.getFileName();
 106                 this.line = ste.getLineNumber();
 107                 return;
 108             }
 109         }
 110 
 111         this.fileName = null;
 112         this.line = 0;
 113     }
 114 
 115     /**
 116      * Get the source file name for this {@code NashornException}
 117      *
 118      * @return the file name
 119      */
 120     public final String getFileName() {
 121         return fileName;
 122     }
 123 
 124     /**
 125      * Get the line number for this {@code NashornException}
 126      *
 127      * @return the line number
 128      */
 129     public final int getLineNumber() {
 130         return line;
 131     }
 132 
 133     /**
 134      * Get the column for this {@code NashornException}
 135      *
 136      * @return the column
 137      */
 138     public final int getColumnNumber() {
 139         return column;
 140     }
 141 
 142     /**
 143      * Returns array javascript stack frames from the given exception object.
 144      *
 145      * @param exception exception from which stack frames are retrieved and filtered
 146      * @return array of javascript stack frames
 147      */
 148     public static StackTraceElement[] getScriptFrames(final Throwable exception) {
 149         final StackTraceElement[] frames = exception.getStackTrace();
 150         final List<StackTraceElement> filtered = new ArrayList<>();
 151         for (final StackTraceElement st : frames) {
 152             if (ECMAErrors.isScriptFrame(st)) {
 153                 final String className = "<" + st.getFileName() + ">";
 154                 String methodName = st.getMethodName();
 155                 if (methodName.equals(CompilerConstants.RUN_SCRIPT.symbolName())) {
 156                     methodName = "<program>";
 157                 }
 158                 filtered.add(new StackTraceElement(className, methodName,
 159                         st.getFileName(), st.getLineNumber()));
 160             }
 161         }
 162         return filtered.toArray(new StackTraceElement[filtered.size()]);
 163     }
 164 
 165     /**
 166      * Return a formatted script stack trace string with frames information separated by '\n'
 167      *
 168      * @param exception exception for which script stack string is returned
 169      * @return formatted stack trace string
 170      */
 171     public static String getScriptStackString(final Throwable exception) {
 172         final StringBuilder buf = new StringBuilder();
 173         final StackTraceElement[] frames = getScriptFrames(exception);
 174         for (final StackTraceElement st : frames) {
 175             buf.append("\tat ");
 176             buf.append(st.getMethodName());
 177             buf.append(" (");
 178             buf.append(st.getFileName());
 179             buf.append(':');
 180             buf.append(st.getLineNumber());
 181             buf.append(")\n");
 182         }
 183         final int len = buf.length();
 184         // remove trailing '\n'
 185         if (len > 0) {
 186             assert buf.charAt(len - 1) == '\n';
 187             buf.deleteCharAt(len - 1);
 188         }
 189         return buf.toString();
 190     }
 191 }