예제 #1
0
 /// <summary>
 /// Updates the Message of a <see cref="JsRuntimeException"/> to be more useful, containing
 /// the line and column numbers.
 /// </summary>
 /// <param name="ex">Original exception</param>
 /// <returns>New exception</returns>
 protected virtual JsRuntimeException WrapJavaScriptRuntimeException(JsRuntimeException ex)
 {
     return(new JsRuntimeException(string.Format(
                                       "{0}\r\nLine: {1}\r\nColumn:{2}",
                                       ex.Message,
                                       ex.LineNumber,
                                       ex.ColumnNumber
                                       ), ex.EngineName, ex.EngineVersion)
     {
         ErrorCode = ex.ErrorCode,
         Category = ex.Category,
         LineNumber = ex.LineNumber,
         ColumnNumber = ex.ColumnNumber,
         SourceFragment = ex.SourceFragment,
         Source = ex.Source,
     });
 }
예제 #2
0
        public void MappingRuntimeErrorDuringRecursiveEvaluationOfFilesIsCorrect()
        {
            // Arrange
            const string directoryPath = "Files/recursive-evaluation/runtime-error";
            const string input         = "evaluateFile('index').calculateResult();";

            // Act
            JsRuntimeException exception = null;

            using (var jsEngine = CreateJsEngine())
            {
                try
                {
                    Func <string, object> evaluateFile = path => {
                        string absolutePath = Path.Combine(directoryPath, $"{path}.js");
                        string code         = File.ReadAllText(absolutePath);
                        object result       = jsEngine.Evaluate(code, absolutePath);

                        return(result);
                    };

                    jsEngine.EmbedHostObject("evaluateFile", evaluateFile);
                    double output = jsEngine.Evaluate <double>(input);
                }
                catch (JsRuntimeException e)
                {
                    exception = e;
                }
            }

            // Assert
            Assert.NotNull(exception);
            Assert.Equal("Runtime error", exception.Category);
            Assert.Equal("'argumens' is not defined", exception.Description);
            Assert.Equal("ReferenceError", exception.Type);
            Assert.Equal("math.js", exception.DocumentName);
            Assert.Equal(10, exception.LineNumber);
            Assert.Equal(4, exception.ColumnNumber);
            Assert.Equal("			result += argumens[i];", exception.SourceFragment);
            Assert.Equal(
                "   at sum (math.js:10:4)" + Environment.NewLine +
                "   at calculateResult (index.js:7:4)" + Environment.NewLine +
                "   at Global code (Script Document:1:1)",
                exception.CallStack
                );
        }
예제 #3
0
        public void MappingHostErrorDuringRecursiveEvaluationOfFilesIsCorrect()
        {
            // Arrange
            const string directoryPath = "Files/recursive-evaluation/host-error";
            const string input         = "evaluateFile('index').calculateResult();";

            // Act
            JsRuntimeException exception = null;

            using (var jsEngine = CreateJsEngine())
            {
                try
                {
                    Func <string, object> evaluateFile = path => {
                        string absolutePath = Path.Combine(directoryPath, $"{path}.js");
                        string code         = File.ReadAllText(absolutePath);
                        object result       = jsEngine.Evaluate(code, absolutePath);

                        return(result);
                    };

                    jsEngine.EmbedHostObject("evaluateFile", evaluateFile);
                    double output = jsEngine.Evaluate <double>(input);
                }
                catch (JsRuntimeException e)
                {
                    exception = e;
                }
            }

            // Assert
            Assert.NotNull(exception);
            Assert.Equal("Runtime error", exception.Category);
            Assert.StartsWith("During invocation of the host delegate an error has occurred - ",
                              exception.Description);
            Assert.Equal("Error", exception.Type);
            Assert.Equal("index.js", exception.DocumentName);
            Assert.Equal(6, exception.LineNumber);
            Assert.Equal(3, exception.ColumnNumber);
            Assert.Equal("		var math = evaluateFile('./match'),", exception.SourceFragment);
            Assert.Equal(
                "   at calculateResult (index.js:6:3)" + Environment.NewLine +
                "   at Global code (Script Document:1:1)",
                exception.CallStack
                );
        }
예제 #4
0
        private JsRuntimeException ConvertMsieJsRuntimeExceptionToJsRuntimeException(
            OriginalJsRuntimeException msieJsRuntimeException)
        {
            var jsRuntimeException = new JsRuntimeException(msieJsRuntimeException.Message,
                                                            ENGINE_NAME, _engineVersion, msieJsRuntimeException)
            {
                ErrorCode      = msieJsRuntimeException.ErrorCode,
                Category       = msieJsRuntimeException.Category,
                LineNumber     = msieJsRuntimeException.LineNumber,
                ColumnNumber   = msieJsRuntimeException.ColumnNumber,
                SourceFragment = msieJsRuntimeException.SourceFragment,
                Source         = msieJsRuntimeException.Source,
                HelpLink       = msieJsRuntimeException.HelpLink
            };

            return(jsRuntimeException);
        }
        /// <summary>
        /// Generates a detailed error message
        /// </summary>
        /// <param name="jsRuntimeException">JS runtime exception</param>
        /// <returns>Detailed error message</returns>
        public static string Format(JsRuntimeException jsRuntimeException)
        {
            var errorMessage = new StringBuilder();

            errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Message,
                                          jsRuntimeException.Message);
            if (!string.IsNullOrWhiteSpace(jsRuntimeException.EngineName))
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_EngineName,
                                              jsRuntimeException.EngineName);
            }
            if (!string.IsNullOrWhiteSpace(jsRuntimeException.EngineVersion))
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_EngineVersion,
                                              jsRuntimeException.EngineVersion);
            }
            if (!string.IsNullOrWhiteSpace(jsRuntimeException.ErrorCode))
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_ErrorCode,
                                              jsRuntimeException.ErrorCode);
            }
            if (!string.IsNullOrWhiteSpace(jsRuntimeException.Category))
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Category,
                                              jsRuntimeException.Category);
            }
            if (jsRuntimeException.LineNumber > 0)
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_LineNumber,
                                              jsRuntimeException.LineNumber.ToString(CultureInfo.InvariantCulture));
            }
            if (jsRuntimeException.ColumnNumber > 0)
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_ColumnNumber,
                                              jsRuntimeException.ColumnNumber.ToString(CultureInfo.InvariantCulture));
            }
            if (!string.IsNullOrWhiteSpace(jsRuntimeException.SourceFragment))
            {
                errorMessage.AppendFormatLine("{1}:{0}{0}{2}", Environment.NewLine,
                                              Strings.ErrorDetails_SourceFragment,
                                              jsRuntimeException.SourceFragment);
            }

            return(errorMessage.ToString());
        }
        public void MappingRuntimeErrorDuringExecutionOfCodeIsCorrect()
        {
            // Arrange
            const string input = @"function factorial(value) {
	if (value <= 0) {
		throw new Error(""The value must be greater than or equal to zero."");
	}

	return value !== 1 ? value * factorial(value - 1) : 1;
}

factorial(5);
factorial(-1);
factorial(0);";

            JsRuntimeException exception = null;

            // Act
            using (var jsEngine = CreateJsEngine())
            {
                try
                {
                    jsEngine.Execute(input, "factorial.js");
                }
                catch (JsRuntimeException e)
                {
                    exception = e;
                }
            }

            // Assert
            Assert.NotNull(exception);
            Assert.Equal("Runtime error", exception.Category);
            Assert.Equal("The value must be greater than or equal to zero.", exception.Description);
            Assert.Equal("Error", exception.Type);
            Assert.Equal("factorial.js", exception.DocumentName);
            Assert.Equal(3, exception.LineNumber);
            Assert.Equal(0, exception.ColumnNumber);
            Assert.Empty(exception.SourceFragment);
            Assert.Equal(
                "   at factorial (factorial.js:3)" + Environment.NewLine +
                "   at Global code (factorial.js:10)",
                exception.CallStack
                );
        }
예제 #7
0
        public void MappingRuntimeErrorDuringExecutionOfPrecompiledCodeIsCorrect()
        {
            // Arrange
            const string input = @"function getItem(items, itemIndex) {
	var item = items[itemIndex];

	return item;
}

(function (getItem) {
	var items = null,
		item = getItem(items, 5)
		;

	return item;
})(getItem);";

            JsRuntimeException exception = null;

            // Act
            using (var jsEngine = CreateJsEngine())
            {
                try
                {
                    IPrecompiledScript precompiledScript = jsEngine.Precompile(input, "get-item.js");
                    jsEngine.Execute(precompiledScript);
                }
                catch (JsRuntimeException e)
                {
                    exception = e;
                }
            }

            // Assert
            Assert.NotNull(exception);
            Assert.Equal("Runtime error", exception.Category);
            Assert.Equal("items is null", exception.Description);
            Assert.Equal("TypeError", exception.Type);
            Assert.Equal("get-item.js", exception.DocumentName);
            Assert.Equal(2, exception.LineNumber);
            Assert.Equal(13, exception.ColumnNumber);
            Assert.Empty(exception.SourceFragment);
            Assert.Empty(exception.CallStack);
        }
		/// <summary>
		/// Generates a detailed error message
		/// </summary>
		/// <param name="jsRuntimeException">JavaScript runtime exception</param>
		/// <returns>Detailed error message</returns>
		public static string Format(JsRuntimeException jsRuntimeException)
		{
			var errorMessage = new StringBuilder();
			errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Message,
				jsRuntimeException.Message);
			if (!string.IsNullOrWhiteSpace(jsRuntimeException.EngineName))
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_EngineName,
					jsRuntimeException.EngineName);
			}
			if (!string.IsNullOrWhiteSpace(jsRuntimeException.EngineVersion))
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_EngineVersion,
					jsRuntimeException.EngineVersion);
			}
			if (!string.IsNullOrWhiteSpace(jsRuntimeException.ErrorCode))
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_ErrorCode,
					jsRuntimeException.ErrorCode);
			}
			if (!string.IsNullOrWhiteSpace(jsRuntimeException.Category))
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Category,
					jsRuntimeException.Category);
			}
			if (jsRuntimeException.LineNumber > 0)
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_LineNumber,
					jsRuntimeException.LineNumber.ToString(CultureInfo.InvariantCulture));
			}
			if (jsRuntimeException.ColumnNumber > 0)
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_ColumnNumber,
					jsRuntimeException.ColumnNumber.ToString(CultureInfo.InvariantCulture));
			}
			if (!string.IsNullOrWhiteSpace(jsRuntimeException.SourceFragment))
			{
				errorMessage.AppendFormatLine("{1}:{0}{0}{2}", Environment.NewLine,
					Strings.ErrorDetails_SourceFragment,
					jsRuntimeException.SourceFragment);
			}

			return errorMessage.ToString();
		}
        public void MappingRuntimeErrorDuringRecursiveExecutionOfFilesIsCorrect()
        {
            // Arrange
            const string directoryPath = "Files/recursive-execution/runtime-error";
            const string variableName  = "num";

            // Act
            JsRuntimeException exception = null;

            using (var jsEngine = CreateJsEngine())
            {
                try
                {
                    Action <string> executeFile = path => jsEngine.ExecuteFile(path);

                    jsEngine.SetVariableValue("directoryPath", directoryPath);
                    jsEngine.EmbedHostObject("executeFile", executeFile);
                    jsEngine.ExecuteFile(Path.Combine(directoryPath, "main-file.js"));

                    int output = jsEngine.GetVariableValue <int>(variableName);
                }
                catch (JsRuntimeException e)
                {
                    exception = e;
                }
            }

            // Assert
            Assert.NotNull(exception);
            Assert.Equal("Runtime error", exception.Category);
            Assert.Equal("nuм is not defined", exception.Description);
            Assert.Equal("ReferenceError", exception.Type);
            Assert.Equal("second-file.js", exception.DocumentName);
            Assert.Equal(1, exception.LineNumber);
            Assert.Equal(1, exception.ColumnNumber);
            Assert.Empty(exception.SourceFragment);
            Assert.Equal(
                "   at Global code (second-file.js:1:1)" + Environment.NewLine +
                "   at Global code (first-file.js:2:1)" + Environment.NewLine +
                "   at Global code (main-file.js:2:1)",
                exception.CallStack
                );
        }
        public void GenerationOfRuntimeErrorMessageIsCorrect()
        {
            // Arrange
            const string input        = @"function getFullName(firstName, lastName) {
	var fullName = firstName + ' ' + middleName + ' ' + lastName;

	return fullName;
}

(function (getFullName) {
	var firstName = 'Vasya',
		lastName = 'Pupkin'
		;

	return getFullName(firstName, lastName);
})(getFullName);";
            string       targetOutput = "ReferenceError: middleName is not defined" + Environment.NewLine +
                                        "   at getFullName (get-full-name.js:2:35) -> 	var fullName = firstName + "+
                                        "' ' + middleName + ' ' + lastName;" + Environment.NewLine +
                                        "   at get-full-name.js:12:9" + Environment.NewLine +
                                        "   at get-full-name.js:13:3"
            ;

            JsRuntimeException exception = null;

            // Act
            using (var jsEngine = CreateJsEngine())
            {
                try
                {
                    IPrecompiledScript precompiledScript = jsEngine.Precompile(input, "get-full-name.js");
                    jsEngine.Execute(precompiledScript);
                }
                catch (JsRuntimeException e)
                {
                    exception = e;
                }
            }

            Assert.NotNull(exception);
            Assert.Equal(targetOutput, exception.Message);
        }
        public void GenerationOfRuntimeErrorMessageIsCorrect()
        {
            // Arrange
            const string input        = @"function foo(x, y) {
	var z = x + y;
	if (z > 20) {
		bar();
	}
}

(function (foo) {
	var a = 8;
	var b = 15;

	foo(a, b);
})(foo);";
            string       targetOutput = "ReferenceError: bar is not defined" + Environment.NewLine +
                                        "   at foo (functions.js:4)" + Environment.NewLine +
                                        "   at Anonymous function (functions.js:12)" + Environment.NewLine +
                                        "   at Global code (functions.js:8)"
            ;

            JsRuntimeException exception = null;

            // Act
            using (var jsEngine = CreateJsEngine())
            {
                try
                {
                    jsEngine.Execute(input, "functions.js");
                }
                catch (JsRuntimeException e)
                {
                    exception = e;
                }
            }

            Assert.NotNull(exception);
            Assert.Equal(targetOutput, exception.Message);
        }
        private JsRuntimeException ConvertJavascriptExceptionToJsRuntimeException(
            OriginalJsException jsException)
        {
            var    jsError = jsException.ErrorObject as OriginalErrorInstance;
            string message = jsException.Message;

            if (jsError != null)
            {
                message = !string.IsNullOrEmpty(jsError.Stack) ? jsError.Stack : jsError.Message;
            }

            var jsRuntimeException = new JsRuntimeException(message, EngineName, EngineVersion,
                                                            jsException)
            {
                Category       = jsException.Name,
                LineNumber     = jsException.LineNumber,
                ColumnNumber   = 0,
                SourceFragment = string.Empty
            };

            return(jsRuntimeException);
        }
예제 #13
0
        private JsRuntimeException ConvertParserExceptionToJsRuntimeException(
            OriginalParserException jsParserException)
        {
            string message = jsParserException.Description;

            if (string.IsNullOrWhiteSpace(message))
            {
                message = jsParserException.Message;
            }

            var jsRuntimeException = new JsRuntimeException(message, ENGINE_NAME, ENGINE_VERSION,
                                                            jsParserException)
            {
                Category     = "ParserError",
                LineNumber   = jsParserException.LineNumber,
                ColumnNumber = jsParserException.Column,
                Source       = jsParserException.Source,
                HelpLink     = jsParserException.HelpLink
            };

            return(jsRuntimeException);
        }
        /// <summary>
        /// Generates a detailed error message
        /// </summary>
        /// <param name="jsRuntimeException">JS runtime exception</param>
        /// <param name="omitMessage">Flag for whether to omit message</param>
        /// <returns>Detailed error message</returns>
        public static string GenerateErrorDetails(JsRuntimeException jsRuntimeException,
                                                  bool omitMessage = false)
        {
            if (jsRuntimeException == null)
            {
                throw new ArgumentNullException(nameof(jsRuntimeException));
            }

            var           stringBuilderPool = StringBuilderPool.Shared;
            StringBuilder detailsBuilder    = stringBuilderPool.Rent();

            WriteCommonErrorDetails(detailsBuilder, jsRuntimeException, omitMessage);
            WriteScriptErrorDetails(detailsBuilder, jsRuntimeException);
            WriteRuntimeErrorDetails(detailsBuilder, jsRuntimeException);

            detailsBuilder.TrimEnd();

            string errorDetails = detailsBuilder.ToString();

            stringBuilderPool.Return(detailsBuilder);

            return(errorDetails);
        }
예제 #15
0
        public virtual void MappingRuntimeErrorDuringExecutionOfCodeIsCorrect()
        {
            // Arrange
            const string input = @"function factorial(value) {
	if (value <= 0) {
		throw new Error(""The value must be greater than or equal to zero."");
	}

	return value !== 1 ? value * factorial(value - 1) : 1;
}

factorial(5);
factorial(@);
factorial(0);";

            JsRuntimeException exception = null;

            // Act
            using (var jsEngine = CreateJsEngine())
            {
                try
                {
                    jsEngine.Execute(input);
                }
                catch (JsRuntimeException e)
                {
                    exception = e;
                }
            }

            // Assert
            Assert.NotNull(exception);
            Assert.IsNotEmpty(exception.Message);
            Assert.AreEqual(10, exception.LineNumber);
            Assert.AreEqual(11, exception.ColumnNumber);
        }
        public void MappingRuntimeErrorDuringStatementsCountOverflowIsCorrect()
        {
            // Arrange
            const string input = @"while (true);";

            JsRuntimeException exception = null;

            // Act
            using (var jsEngine = new JintJsEngine(
                       new JintSettings
            {
                MaxStatements = 5
            }
                       ))
            {
                try
                {
                    jsEngine.Execute(input, "infinite-loop.js");
                }
                catch (JsRuntimeException e)
                {
                    exception = e;
                }
            }

            // Assert
            Assert.NotNull(exception);
            Assert.Equal("Runtime error", exception.Category);
            Assert.Equal("The maximum number of statements executed have been reached.", exception.Description);
            Assert.Equal("RangeError", exception.Type);
            Assert.Empty(exception.DocumentName);
            Assert.Equal(0, exception.LineNumber);
            Assert.Equal(0, exception.ColumnNumber);
            Assert.Empty(exception.SourceFragment);
            Assert.Empty(exception.CallStack);
        }
        private JsRuntimeException ConvertParserExceptionToJsRuntimeException(
            OriginalParserException jsParserException)
        {
            const string category     = "ParserError";
            string       description  = jsParserException.Description;
            int          lineNumber   = jsParserException.LineNumber;
            int          columnNumber = jsParserException.Column;
            string       message      = !string.IsNullOrWhiteSpace(description) ?
                                        GenerateErrorMessageWithLocation(category, description, jsParserException.Source,
                                                                         lineNumber, columnNumber)
                                :
                                        jsParserException.Message
            ;

            var jsRuntimeException = new JsRuntimeException(message, EngineName, EngineVersion,
                                                            jsParserException)
            {
                Category     = category,
                LineNumber   = lineNumber,
                ColumnNumber = columnNumber
            };

            return(jsRuntimeException);
        }
 public static string Format(JsRuntimeException jsRuntimeException)
 {
     return(GenerateErrorDetails(jsRuntimeException));
 }
        public void MappingRuntimeErrorDuringRecursionDepthOverflowIsCorrect()
        {
            // Arrange
            const string input = @"function fibonacci(n) {
	if (n === 1) {
		return 1;
	}
	else if (n === 2) {
		return 1;
	}
	else {
		return fibonacci(n - 1) + fibonacci(n - 2);
	}
}

(function (fibonacci) {
	var a = 5;
	var b = 11;
	var c = fibonacci(b) - fibonacci(a);
})(fibonacci);";

            JsRuntimeException exception = null;

            // Act
            using (var jsEngine = new JintJsEngine(
                       new JintSettings
            {
                MaxRecursionDepth = 5
            }
                       ))
            {
                try
                {
                    jsEngine.Execute(input, "fibonacci.js");
                }
                catch (JsRuntimeException e)
                {
                    exception = e;
                }
            }

            // Assert
            Assert.NotNull(exception);
            Assert.Equal("Runtime error", exception.Category);
            Assert.Equal("The recursion is forbidden by script host.", exception.Description);
            Assert.Equal("RangeError", exception.Type);
            Assert.Empty(exception.DocumentName);
            Assert.Equal(0, exception.LineNumber);
            Assert.Equal(0, exception.ColumnNumber);
            Assert.Empty(exception.SourceFragment);
            Assert.Equal(
                "   at fibonacci" + Environment.NewLine +
                "   at fibonacci" + Environment.NewLine +
                "   at fibonacci" + Environment.NewLine +
                "   at fibonacci" + Environment.NewLine +
                "   at fibonacci" + Environment.NewLine +
                "   at fibonacci" + Environment.NewLine +
                "   at Anonymous function",
                exception.CallStack
                );
        }
        private JsRuntimeException ConvertJavaScriptExceptionToJsRuntimeException(
            JavaScriptException jsException)
        {
            string message        = jsException.Message;
            string category       = string.Empty;
            int    lineNumber     = 0;
            int    columnNumber   = 0;
            string sourceFragment = string.Empty;

            if (jsException is JavaScriptScriptException)
            {
                category = "Script error";

                var             jsScriptException = (JavaScriptScriptException)jsException;
                JavaScriptValue errorValue        = jsScriptException.Error;

                JavaScriptPropertyId messagePropertyId    = JavaScriptPropertyId.FromString("message");
                JavaScriptValue      messagePropertyValue = errorValue.GetProperty(messagePropertyId);
                string scriptMessage = messagePropertyValue.ConvertToString().ToString();
                if (!string.IsNullOrWhiteSpace(scriptMessage))
                {
                    message = string.Format("{0}: {1}", message.TrimEnd('.'), scriptMessage);
                }

                JavaScriptPropertyId linePropertyId = JavaScriptPropertyId.FromString("line");
                if (errorValue.HasProperty(linePropertyId))
                {
                    JavaScriptValue linePropertyValue = errorValue.GetProperty(linePropertyId);
                    lineNumber = (int)linePropertyValue.ConvertToNumber().ToDouble() + 1;
                }

                JavaScriptPropertyId columnPropertyId = JavaScriptPropertyId.FromString("column");
                if (errorValue.HasProperty(columnPropertyId))
                {
                    JavaScriptValue columnPropertyValue = errorValue.GetProperty(columnPropertyId);
                    columnNumber = (int)columnPropertyValue.ConvertToNumber().ToDouble() + 1;
                }

                JavaScriptPropertyId sourcePropertyId = JavaScriptPropertyId.FromString("source");
                if (errorValue.HasProperty(sourcePropertyId))
                {
                    JavaScriptValue sourcePropertyValue = errorValue.GetProperty(sourcePropertyId);
                    sourceFragment = sourcePropertyValue.ConvertToString().ToString();
                }
            }
            else if (jsException is JavaScriptUsageException)
            {
                category = "Usage error";
            }
            else if (jsException is JavaScriptEngineException)
            {
                category = "Engine error";
            }
            else if (jsException is JavaScriptFatalException)
            {
                category = "Fatal error";
            }

            var jsEngineException = new JsRuntimeException(message, ENGINE_MODE_NAME)
            {
                ErrorCode      = ((uint)jsException.ErrorCode).ToString(CultureInfo.InvariantCulture),
                Category       = category,
                LineNumber     = lineNumber,
                ColumnNumber   = columnNumber,
                SourceFragment = sourceFragment,
                HelpLink       = jsException.HelpLink
            };

            return(jsEngineException);
        }
예제 #21
0
        private JsRuntimeException ConvertJsExceptionToJsRuntimeException(
            JsException jsException)
        {
            string message        = jsException.Message;
            string category       = string.Empty;
            int    lineNumber     = 0;
            int    columnNumber   = 0;
            string sourceFragment = string.Empty;

            var jsScriptException = jsException as IeJsScriptException;

            if (jsScriptException != null)
            {
                category = "Script error";
                IeJsValue errorValue = jsScriptException.Error;

                IeJsPropertyId stackPropertyId = IeJsPropertyId.FromString("stack");
                if (errorValue.HasProperty(stackPropertyId))
                {
                    IeJsValue stackPropertyValue = errorValue.GetProperty(stackPropertyId);
                    message = stackPropertyValue.ConvertToString().ToString();
                }
                else
                {
                    IeJsValue messagePropertyValue = errorValue.GetProperty("message");
                    string    scriptMessage        = messagePropertyValue.ConvertToString().ToString();
                    if (!string.IsNullOrWhiteSpace(scriptMessage))
                    {
                        message = string.Format("{0}: {1}", message.TrimEnd('.'), scriptMessage);
                    }
                }

                IeJsPropertyId linePropertyId = IeJsPropertyId.FromString("line");
                if (errorValue.HasProperty(linePropertyId))
                {
                    IeJsValue linePropertyValue = errorValue.GetProperty(linePropertyId);
                    lineNumber = (int)linePropertyValue.ConvertToNumber().ToDouble() + 1;
                }

                IeJsPropertyId columnPropertyId = IeJsPropertyId.FromString("column");
                if (errorValue.HasProperty(columnPropertyId))
                {
                    IeJsValue columnPropertyValue = errorValue.GetProperty(columnPropertyId);
                    columnNumber = (int)columnPropertyValue.ConvertToNumber().ToDouble() + 1;
                }

                if (lineNumber <= 0 && columnNumber <= 0)
                {
                    GetErrorCoordinatesFromMessage(message, out lineNumber, out columnNumber);
                }

                IeJsPropertyId sourcePropertyId = IeJsPropertyId.FromString("source");
                if (errorValue.HasProperty(sourcePropertyId))
                {
                    IeJsValue sourcePropertyValue = errorValue.GetProperty(sourcePropertyId);
                    sourceFragment = sourcePropertyValue.ConvertToString().ToString();
                }
            }
            else if (jsException is JsUsageException)
            {
                category = "Usage error";
            }
            else if (jsException is JsEngineException)
            {
                category = "Engine error";
            }
            else if (jsException is JsFatalException)
            {
                category = "Fatal error";
            }

            var jsEngineException = new JsRuntimeException(message, _engineModeName)
            {
                ErrorCode      = ((uint)jsException.ErrorCode).ToString(CultureInfo.InvariantCulture),
                Category       = category,
                LineNumber     = lineNumber,
                ColumnNumber   = columnNumber,
                SourceFragment = sourceFragment
            };

            return(jsEngineException);
        }
예제 #22
0
        private static JsRuntimeException ConvertJsExceptionToJsRuntimeException(
            OriginalJsException jsException)
        {
            string message        = jsException.Message;
            string category       = string.Empty;
            int    lineNumber     = 0;
            int    columnNumber   = 0;
            string sourceFragment = string.Empty;

            var jsScriptException = jsException as JsScriptException;

            if (jsScriptException != null)
            {
                category = "Script error";
                JsValue errorValue = jsScriptException.Error;

                JsPropertyId stackPropertyId = JsPropertyId.FromString("stack");
                if (errorValue.HasProperty(stackPropertyId))
                {
                    JsValue stackPropertyValue = errorValue.GetProperty(stackPropertyId);
                    message = stackPropertyValue.ConvertToString().ToString();
                }
                else
                {
                    JsValue messagePropertyValue = errorValue.GetProperty("message");
                    string  scriptMessage        = messagePropertyValue.ConvertToString().ToString();
                    if (!string.IsNullOrWhiteSpace(scriptMessage))
                    {
                        message = string.Format("{0}: {1}", message.TrimEnd('.'), scriptMessage);
                    }
                }

                JsPropertyId linePropertyId = JsPropertyId.FromString("line");
                if (errorValue.HasProperty(linePropertyId))
                {
                    JsValue linePropertyValue = errorValue.GetProperty(linePropertyId);
                    lineNumber = linePropertyValue.ConvertToNumber().ToInt32() + 1;
                }

                JsPropertyId columnPropertyId = JsPropertyId.FromString("column");
                if (errorValue.HasProperty(columnPropertyId))
                {
                    JsValue columnPropertyValue = errorValue.GetProperty(columnPropertyId);
                    columnNumber = columnPropertyValue.ConvertToNumber().ToInt32() + 1;
                }

                if (lineNumber <= 0 && columnNumber <= 0)
                {
                    Match errorStringMatch = _errorStringRegex.Match(message);
                    if (errorStringMatch.Success)
                    {
                        GroupCollection errorStringGroups = errorStringMatch.Groups;

                        lineNumber   = int.Parse(errorStringGroups["lineNumber"].Value);
                        columnNumber = int.Parse(errorStringGroups["columnNumber"].Value);
                    }
                }

                JsPropertyId sourcePropertyId = JsPropertyId.FromString("source");
                if (errorValue.HasProperty(sourcePropertyId))
                {
                    JsValue sourcePropertyValue = errorValue.GetProperty(sourcePropertyId);
                    sourceFragment = sourcePropertyValue.ConvertToString().ToString();
                }
            }
            else if (jsException is JsUsageException)
            {
                category = "Usage error";
            }
            else if (jsException is JsEngineException)
            {
                category = "Engine error";
            }
            else if (jsException is JsFatalException)
            {
                category = "Fatal error";
            }

            var jsEngineException = new JsRuntimeException(message, EngineName, EngineVersion)
            {
                ErrorCode      = ((uint)jsException.ErrorCode).ToString(CultureInfo.InvariantCulture),
                Category       = category,
                LineNumber     = lineNumber,
                ColumnNumber   = columnNumber,
                SourceFragment = sourceFragment
            };

            return(jsEngineException);
        }