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 import jdk.nashorn.internal.runtime.ScriptObject;
  33 
  34 /**
  35  * This is base exception for all Nashorn exceptions. These originate from
  36  * user's ECMAScript code. Example: script parse errors, exceptions thrown from
  37  * scripts. Note that ScriptEngine methods like "eval", "invokeMethod",
  38  * "invokeFunction" will wrap this as ScriptException and throw it. But, there
  39  * are cases where user may need to access this exception (or implementation
  40  * defined subtype of this). For example, if java interface is implemented by a
  41  * script object or Java access to script object properties via java.util.Map
  42  * interface. In these cases, user code will get an instance of this or
  43  * implementation defined subclass.
  44  */
  45 @SuppressWarnings("serial")
  46 public abstract class NashornException extends RuntimeException {
  47     // script file name
  48     private final String fileName;
  49     // script line number
  50     private final int line;
  51     // script column number
  52     private final int column;
  53     // underlying ECMA error object - lazily initialized
  54     private Object ecmaError;
  55 
  56     /** script source name used for "engine.js" */
  57     public static final String ENGINE_SCRIPT_SOURCE_NAME = "nashorn:engine/resources/engine.js";
  58 
  59     /**
  60      * Constructor
  61      *
  62      * @param msg       exception message
  63      * @param fileName  file name
  64      * @param line      line number
  65      * @param column    column number
  66      */
  67     protected NashornException(final String msg, final String fileName, final int line, final int column) {
  68         this(msg, null, fileName, line, column);
  69     }
  70 
  71     /**
  72      * Constructor
  73      *
  74      * @param msg       exception message
  75      * @param cause     exception cause
  76      * @param fileName  file name
  77      * @param line      line number
  78      * @param column    column number
  79      */
  80     protected NashornException(final String msg, final Throwable cause, final String fileName, final int line, final int column) {
  81         super(msg, cause == null ? null : cause);
  82         this.fileName = fileName;
  83         this.line = line;
  84         this.column = column;
  85     }
  86 
  87     /**
  88      * Constructor
  89      *
  90      * @param msg       exception message
  91      * @param cause     exception cause
  92      */
  93     protected NashornException(final String msg, final Throwable cause) {
  94         super(msg, cause == null ? null : cause);
  95         // This is not so pretty - but it gets the job done. Note that the stack
  96         // trace has been already filled by "fillInStackTrace" call from
  97         // Throwable
  98         // constructor and so we don't pay additional cost for it.
  99 
 100         // Hard luck - no column number info
 101         this.column = -1;
 102 
 103         // Find the first JavaScript frame by walking and set file, line from it
 104         // Usually, we should be able to find it in just few frames depth.
 105         for (final StackTraceElement ste : getStackTrace()) {
 106             if (ECMAErrors.isScriptFrame(ste)) {
 107                 // Whatever here is compiled from JavaScript code
 108                 this.fileName = ste.getFileName();
 109                 this.line = ste.getLineNumber();
 110                 return;
 111             }
 112         }
 113 
 114         this.fileName = null;
 115         this.line = 0;
 116     }
 117 
 118     /**
 119      * Get the source file name for this {@code NashornException}
 120      *
 121      * @return the file name
 122      */
 123     public final String getFileName() {
 124         return fileName;
 125     }
 126 
 127     /**
 128      * Get the line number for this {@code NashornException}
 129      *
 130      * @return the line number
 131      */
 132     public final int getLineNumber() {
 133         return line;
 134     }
 135 
 136     /**
 137      * Get the column for this {@code NashornException}
 138      *
 139      * @return the column
 140      */
 141     public final int getColumnNumber() {
 142         return column;
 143     }
 144 
 145     /**
 146      * Returns array javascript stack frames from the given exception object.
 147      *
 148      * @param exception exception from which stack frames are retrieved and filtered
 149      * @return array of javascript stack frames
 150      */
 151     public static StackTraceElement[] getScriptFrames(final Throwable exception) {
 152         final StackTraceElement[] frames = exception.getStackTrace();
 153         final List<StackTraceElement> filtered = new ArrayList<>();
 154         for (final StackTraceElement st : frames) {
 155             if (ECMAErrors.isScriptFrame(st)) {
 156                 final String className = "<" + st.getFileName() + ">";
 157                 String methodName = st.getMethodName();
 158                 if (methodName.equals(CompilerConstants.RUN_SCRIPT.symbolName())) {
 159                     methodName = "<program>";
 160                 }
 161                 filtered.add(new StackTraceElement(className, methodName,
 162                         st.getFileName(), st.getLineNumber()));
 163             }
 164         }
 165         return filtered.toArray(new StackTraceElement[filtered.size()]);
 166     }
 167 
 168     /**
 169      * Return a formatted script stack trace string with frames information separated by '\n'
 170      *
 171      * @param exception exception for which script stack string is returned
 172      * @return formatted stack trace string
 173      */
 174     public static String getScriptStackString(final Throwable exception) {
 175         final StringBuilder buf = new StringBuilder();
 176         final StackTraceElement[] frames = getScriptFrames(exception);
 177         for (final StackTraceElement st : frames) {
 178             buf.append("\tat ");
 179             buf.append(st.getMethodName());
 180             buf.append(" (");
 181             buf.append(st.getFileName());
 182             buf.append(':');
 183             buf.append(st.getLineNumber());
 184             buf.append(")\n");
 185         }
 186         final int len = buf.length();
 187         // remove trailing '\n'
 188         if (len > 0) {
 189             assert buf.charAt(len - 1) == '\n';
 190             buf.deleteCharAt(len - 1);
 191         }
 192         return buf.toString();
 193     }
 194     
 195     protected Object getThrown() {
 196         return null;
 197     }
 198     
 199     protected NashornException initEcmaError(final ScriptObject global) {
 200         if (ecmaError != null) {
 201             return this; // initialized already!
 202         }
 203         
 204         final Object thrown = getThrown();
 205         if (thrown instanceof ScriptObject) {
 206             ecmaError = ScriptObjectMirror.wrap(thrown, global);
 207         } else {
 208             ecmaError = thrown;
 209         }
 210         
 211         return this;
 212     }
 213 
 214     /**
 215      * Return the underlying ECMA error object, if available.
 216      *
 217      * @return underlying ECMA Error object's mirror or whatever was thrown
 218      *         from script such as a String, Number or a Boolean.
 219      */    
 220     public Object getEcmaError() {
 221         return ecmaError;
 222     }
 223 }
--- EOF ---