Exemple #1
0
        public async Task TryInvokeAsync_ThrowsInvocationExceptionIfHttpResponseHasAnUnexpectedStatusCode()
        {
            // Arrange
            var dummyInvocationRequest = new InvocationRequest(ModuleSourceType.Cache, "dummyModuleSource");
            Mock <HttpContent>         mockRequestHttpContent = _mockRepository.Create <HttpContent>(); // HttpContent is an abstract class
            Mock <IHttpContentFactory> mockHttpContentFactory = _mockRepository.Create <IHttpContentFactory>();

            mockHttpContentFactory.Setup(h => h.Create(dummyInvocationRequest)).Returns(mockRequestHttpContent.Object);
            const HttpStatusCode dummyHttpStatusCode        = HttpStatusCode.NoContent;
            var dummyHttpResponseMessage                    = new HttpResponseMessage(dummyHttpStatusCode);
            Mock <IHttpClientService> mockHttpClientService = _mockRepository.Create <IHttpClientService>();

            mockHttpClientService.Setup(h => h.SendAsync(It.Is <HttpRequestMessage>(hr => ReferenceEquals(hr.Content, mockRequestHttpContent.Object)),
                                                         HttpCompletionOption.ResponseHeadersRead,
                                                         CancellationToken.None)).
            ReturnsAsync(dummyHttpResponseMessage);
#pragma warning disable IDE0067
            ExposedHttpNodeJSService testSubject = CreateHttpNodeJSService(httpContentFactory: mockHttpContentFactory.Object, httpClientService: mockHttpClientService.Object);
#pragma warning disable IDE0067

            // Act and assert
            InvocationException result = await Assert.ThrowsAsync <InvocationException>(() => testSubject.ExposedTryInvokeAsync <string>(dummyInvocationRequest, CancellationToken.None)).ConfigureAwait(false);

            // Assert
            _mockRepository.VerifyAll();
            Assert.Equal(string.Format(Strings.InvocationException_HttpNodeJSService_UnexpectedStatusCode, dummyHttpStatusCode), result.Message);
        }
Exemple #2
0
        public async Task TryInvokeAsync_ThrowsInvocationExceptionIfHttpResponseHas500StatusCode()
        {
            // Arrange
            var dummyInvocationRequest = new InvocationRequest(ModuleSourceType.Cache, "dummyModuleSource");
            Mock <HttpContent>         mockRequestHttpContent = _mockRepository.Create <HttpContent>(); // HttpContent is an abstract class
            Mock <IHttpContentFactory> mockHttpContentFactory = _mockRepository.Create <IHttpContentFactory>();

            mockHttpContentFactory.Setup(h => h.Create(dummyInvocationRequest)).Returns(mockRequestHttpContent.Object);
            var dummyHttpResponseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StreamContent(new MemoryStream())
            };
            Mock <IHttpClientService> mockHttpClientService = _mockRepository.Create <IHttpClientService>();

            mockHttpClientService.Setup(h => h.SendAsync(It.Is <HttpRequestMessage>(hr => ReferenceEquals(hr.Content, mockRequestHttpContent.Object)),
                                                         HttpCompletionOption.ResponseHeadersRead,
                                                         CancellationToken.None)).
            ReturnsAsync(dummyHttpResponseMessage);
            var dummyInvocationError            = new InvocationError("dummyErrorMessage", "dummyErrorStack");
            Mock <IJsonService> mockJsonService = _mockRepository.Create <IJsonService>();

            mockJsonService.Setup(j => j.DeserializeAsync <InvocationError>(It.IsAny <Stream>(), CancellationToken.None)).ReturnsAsync(dummyInvocationError);
#pragma warning disable IDE0067
            ExposedHttpNodeJSService testSubject = CreateHttpNodeJSService(httpContentFactory: mockHttpContentFactory.Object,
                                                                           httpClientService: mockHttpClientService.Object,
                                                                           jsonService: mockJsonService.Object);
#pragma warning disable IDE0067

            // Act and assert
            InvocationException result = await Assert.ThrowsAsync <InvocationException>(() => testSubject.ExposedTryInvokeAsync <string>(dummyInvocationRequest, CancellationToken.None)).ConfigureAwait(false);

            _mockRepository.VerifyAll();
            Assert.Equal(dummyInvocationError.ErrorMessage + Environment.NewLine + dummyInvocationError.ErrorStack, result.Message, ignoreLineEndingDifferences: true);
        }
        protected async Task <InvokeReply> InvokeAsync(InvokeRequest request, ServerCallContext context)
        {
            var method        = request.Method;
            var correlationId = request.CorrelationId;
            var action        = _commandableMethods?[method];

            // Handle method not found
            if (action == null)
            {
                var err = new InvocationException(correlationId, "METHOD_NOT_FOUND", "Method " + method + " was not found")
                          .WithDetails("method", method);

                return(CreateErrorResponse(err));
            }

            try
            {
                // Convert arguments
                var argsEmpty = request.ArgsEmpty;
                var argsJson  = request.ArgsJson;
                var args      = !argsEmpty && !string.IsNullOrWhiteSpace(argsJson)
                                        ? Parameters.FromJson(argsJson)
                                        : new Parameters();

                // Todo: Validate schema
                //var schema = this._commandableSchemas[method];
                //if (schema)
                //{
                //    //...
                //}

                // Call command action
                var result = await action(correlationId, args);

                // Process result and generate response
                var response = new InvokeReply
                {
                    Error       = null,
                    ResultEmpty = result == null
                };

                if (result != null)
                {
                    response.ResultJson = JsonConverter.ToJson(result);
                }

                return(response);
            }
            catch (Exception ex)
            {
                // Handle unexpected exception
                var err = new InvocationException(correlationId, "METHOD_FAILED", "Method " + method + " failed")
                          .Wrap(ex).WithDetails("method", method);

                return(CreateErrorResponse(err));
            }
        }
        public static InvocationTarget Create(object @object, string methodName, List <Parameter> parameters)
        {
            var method = @object.GetType().GetTypeInfo().GetDeclaredMethod(methodName);

            if (method == null)
            {
                throw InvocationException.MissingMethod(@object, methodName);
            }

            var methodParameters = method.GetParameters();

            // now then, for each method parameter we see if we can get the appropriate value from the jsonParameters
            // and if so
            // add that to our list of value for the invocation...

            var paramValues = new List <object>();

            foreach (var methodParameter in methodParameters)
            {
                var name = methodParameter.Name;

                var parameter = parameters.FirstOrDefault(p => p.Name == name);

                if (parameter != null)
                {
                    // we have a match !
                    var paramValue = parameter.Value;

                    var paramString = paramValue.ToString();

                    try
                    {
                        // now deserialize using the type of the parameters
                        var value = JsonConvert.DeserializeObject(paramString, methodParameter.ParameterType);

                        paramValues.Add(value);
                    }
                    catch (Exception)
                    {
                        throw InvocationException.InvalidParameterValue(@object, methodName, name, paramString);
                    }
                }
                else
                {
                    // do we do anything here, i.e. we've not had a parameter value through
                    if (!methodParameter.HasDefaultValue)
                    {
                        // need to throw an exception ...
                        throw InvocationException.ParameterNotOptional(@object, methodName, methodParameter.Name);
                    }
                }
            }

            return(new InvocationTarget(@object, method, paramValues.ToArray()));
        }
        public async void AllInvokeMethods_ThrowInvocationExceptionIfNoExportNameSpecifiedAndModuleExportsIsNotAFunction()
        {
            // Arrange
            HttpNodeJSService testSubject = CreateHttpNodeJSService();

            // Act
            InvocationException result = await Assert.ThrowsAsync <InvocationException>(() =>
                                                                                        testSubject.InvokeFromStringAsync <DummyResult>("module.exports = {result: 'not a function'};")).
                                         ConfigureAwait(false);

            // Assert
            Assert.StartsWith("The module \"module.exports = {result:...\" does not export a function.", result.Message);
        }
        /// <summary>
        /// 递交错误处理。
        /// </summary>
        public override void Handle(Exception exception)
        {
            InvocationException ex = exception as InvocationException;

            if (ex == null)
            {
                throw new ArgumentException("类型不对,请传入 InvocationException");
            }

            string msg = "程序调用出错,路径为" + ex.InvocationPath;

            Log.Error(msg, ex);
        }
        public async void AllInvokeMethods_ThrowInvocationExceptionIfInvokedAsyncMethodThrowsError()
        {
            // Arrange
            const string      dummyErrorString = "error";
            HttpNodeJSService testSubject      = CreateHttpNodeJSService();

            // Act
            InvocationException result = await Assert.ThrowsAsync <InvocationException>(() =>
                                                                                        testSubject.InvokeFromStringAsync <DummyResult>("module.exports = async (errorString) => {throw new Error(errorString);}", args: new[] { dummyErrorString })).
                                         ConfigureAwait(false);

            // Assert
            Assert.StartsWith(dummyErrorString, result.Message); // Complete message includes the stack
        }
        public async void AllInvokeMethods_ThrowInvocationExceptionIfModuleExportWithSpecifiedExportNameIsNotAFunction()
        {
            // Arrange
            const string      dummyExportName = "dummyExportName";
            HttpNodeJSService testSubject     = CreateHttpNodeJSService();

            // Act
            InvocationException result = await Assert.ThrowsAsync <InvocationException>(() =>
                                                                                        testSubject.InvokeFromStringAsync <DummyResult>($"module.exports = {{{dummyExportName}: 'not a function'}};", exportName: dummyExportName)).
                                         ConfigureAwait(false);

            // Assert
            Assert.StartsWith($"The export named {dummyExportName} from module \"module.exports = {{dummyEx...\" is not a function.", result.Message);
        }
        public async void AllInvokeMethods_ThrowInvocationExceptionIfThereIsNoModuleExportWithSpecifiedExportName()
        {
            // Arrange
            const string      dummyExportName = "dummyExportName";
            HttpNodeJSService testSubject     = CreateHttpNodeJSService();

            // Act
            InvocationException result = await Assert.ThrowsAsync <InvocationException>(() =>
                                                                                        testSubject.InvokeFromStringAsync <DummyResult>("module.exports = (callback) => callback(null, {result: 'success'});", DUMMY_CACHE_IDENTIFIER, dummyExportName)).
                                         ConfigureAwait(false);

            // Assert
            Assert.StartsWith($"The module {DUMMY_CACHE_IDENTIFIER} has no export named {dummyExportName}.", result.Message);
        }
        public async void AllInvokeMethods_ThrowInvocationExceptionIfModuleHasNoExports()
        {
            // Arrange
            const string      dummyModule = "return null;";
            HttpNodeJSService testSubject = CreateHttpNodeJSService();

            // Act
            InvocationException result = await Assert.ThrowsAsync <InvocationException>(() =>
                                                                                        testSubject.InvokeFromStringAsync <DummyResult>(dummyModule)).
                                         ConfigureAwait(false);

            // Assert
            Assert.StartsWith($"The module \"{dummyModule}...\" has no exports. Ensure that the module assigns a function or an object containing functions to module.exports.", result.Message);
        }
Exemple #11
0
        public static IEnumerable <object?[]> Constructor_JoinsMessageAndStackParameters_Data()
        {
            string frameworkGeneratedMessage = new InvocationException().Message; // If no message is supplied to Exception, the framework generates a default

            return(new object?[][]
            {
                new object?[] { "dummyMessage", "dummyStack", "dummyMessage\ndummyStack" },
                new object?[] { null, "dummyStack", "dummyStack" },
                new object?[] { "dummyMessage", null, "dummyMessage" },
                new object?[] { null, null, frameworkGeneratedMessage },
                new object?[] { string.Empty, "dummyStack", "dummyStack" },
                new object?[] { "dummyMessage", string.Empty, "dummyMessage" },
                new object?[] { string.Empty, string.Empty, string.Empty }
            });
        }
Exemple #12
0
        public void InvocationException_CanBeSerialized()
        {
            // Arrange
            const string dummyMessage   = "dummyMessage";
            IFormatter   dummyFormatter = new BinaryFormatter();
            var          dummyStream    = new MemoryStream();
            var          testSubject    = new InvocationException(dummyMessage);

            // Act
            dummyFormatter.Serialize(dummyStream, testSubject);
            dummyStream.Position = 0;
            var result = (InvocationException)dummyFormatter.Deserialize(dummyStream);

            // Assert
            Assert.Equal(dummyMessage, result.Message);
        }
Exemple #13
0
 private void OnRemotingMessageReceived(object sender, RemotingMessageReceivedEventArgs e)
 {
     try
     {
         // ISSUE: reference to a compiler-generated field
         EventHandler <RemotingMessageReceivedEventArgs> remotingMessageReceived = this.RemotingMessageReceived;
         if (remotingMessageReceived != null)
         {
             RemotingMessageReceivedEventArgs e1 = e;
             remotingMessageReceived((object)this, e1);
         }
         e.Result = this._remote.InvokeAckAsync(e.InvokeId, e.Message).Result;
         // ISSUE: reference to a compiler-generated field
         EventHandler <RemotingMessageReceivedEventArgs> acknowledgeMessageReceived = this.AcknowledgeMessageReceived;
         if (acknowledgeMessageReceived == null)
         {
             return;
         }
         RemotingMessageReceivedEventArgs e2 = e;
         acknowledgeMessageReceived((object)this, e2);
     }
     catch (AggregateException ex)
     {
         InvocationException innerException = ex.InnerException as InvocationException;
         if (innerException != null)
         {
             e.Error = (ErrorMessage)innerException.SourceException;
             // ISSUE: reference to a compiler-generated field
             EventHandler <RemotingMessageReceivedEventArgs> errorMessageReceived = this.ErrorMessageReceived;
             if (errorMessageReceived == null)
             {
                 return;
             }
             RemotingMessageReceivedEventArgs e1 = e;
             errorMessageReceived((object)this, e1);
         }
         else
         {
             throw;
         }
     }
 }
        private WrapperException WrapInvocationException(InvocationException originalException)
        {
            WrapperException wrapperException;
            string           message     = originalException.Message;
            string           description = string.Empty;

            if (_timeoutErrorMessage.IsMatch(message))
            {
                message     = CoreStrings.Runtime_ScriptTimeoutExceeded;
                description = message;

                var wrapperTimeoutException = new WrapperTimeoutException(message, EngineName, _engineVersion,
                                                                          originalException)
                {
                    Description = description
                };

                return(wrapperTimeoutException);
            }

            string documentName = string.Empty;
            int    lineNumber   = 0;
            int    columnNumber = 0;
            string sourceLine   = string.Empty;

            Match detailsMatch  = _errorDetailsRegex.Match(message);
            int   detailsLength = 0;

            if (detailsMatch.Success)
            {
                GroupCollection detailsGroups = detailsMatch.Groups;
                description  = detailsGroups["description"].Value;
                documentName = detailsGroups["documentName"].Success ?
                               detailsGroups["documentName"].Value : string.Empty;
                lineNumber = detailsGroups["lineNumber"].Success ?
                             int.Parse(detailsGroups["lineNumber"].Value) : 0;
                columnNumber = NodeJsErrorHelpers.GetColumnCountFromLine(detailsGroups["pointer"].Value);
                sourceLine   = detailsGroups["sourceLine"].Value;

                detailsLength = detailsMatch.Length;
            }

            message = detailsLength > 0 ? message.Substring(detailsLength) : message;

            Match messageWithTypeMatch = _errorMessageWithTypeRegex.Match(message);

            if (messageWithTypeMatch.Success)
            {
                GroupCollection messageWithTypeGroups = messageWithTypeMatch.Groups;
                string          type = messageWithTypeGroups["type"].Value;
                description = messageWithTypeGroups["description"].Value;
                string sourceFragment = TextHelpers.GetTextFragmentFromLine(sourceLine, columnNumber);

                WrapperScriptException wrapperScriptException;
                if (type == JsErrorType.Syntax)
                {
                    message = JsErrorHelpers.GenerateScriptErrorMessage(type, description, documentName,
                                                                        lineNumber, columnNumber, sourceFragment);

                    wrapperScriptException = new WrapperCompilationException(message, EngineName, _engineVersion,
                                                                             originalException);
                }
                else if (type == "UsageError")
                {
                    wrapperException = new WrapperUsageException(description, EngineName, _engineVersion,
                                                                 originalException);
                    wrapperException.Description = description;

                    return(wrapperException);
                }
                else
                {
                    var errorLocationItems    = new ErrorLocationItem[0];
                    int messageLength         = message.Length;
                    int messageWithTypeLength = messageWithTypeMatch.Length;

                    if (messageWithTypeLength < messageLength)
                    {
                        string errorLocation = message.Substring(messageWithTypeLength);
                        errorLocationItems = NodeJsErrorHelpers.ParseErrorLocation(errorLocation);
                        errorLocationItems = FilterErrorLocationItems(errorLocationItems);

                        if (errorLocationItems.Length > 0)
                        {
                            ErrorLocationItem firstErrorLocationItem = errorLocationItems[0];
                            documentName = firstErrorLocationItem.DocumentName;
                            lineNumber   = firstErrorLocationItem.LineNumber;
                            columnNumber = firstErrorLocationItem.ColumnNumber;

                            firstErrorLocationItem.SourceFragment = sourceFragment;
                        }
                    }

                    string callStack = JsErrorHelpers.StringifyErrorLocationItems(errorLocationItems, true);
                    string callStackWithSourceFragment = JsErrorHelpers.StringifyErrorLocationItems(
                        errorLocationItems);
                    message = JsErrorHelpers.GenerateScriptErrorMessage(type, description,
                                                                        callStackWithSourceFragment);

                    wrapperScriptException = new WrapperRuntimeException(message, EngineName, _engineVersion,
                                                                         originalException)
                    {
                        CallStack = callStack
                    };
                }

                wrapperScriptException.Type           = type;
                wrapperScriptException.DocumentName   = documentName;
                wrapperScriptException.LineNumber     = lineNumber;
                wrapperScriptException.ColumnNumber   = columnNumber;
                wrapperScriptException.SourceFragment = sourceFragment;

                wrapperException = wrapperScriptException;
            }
            else
            {
                wrapperException = new WrapperException(message, EngineName, _engineVersion,
                                                        originalException);
            }

            wrapperException.Description = description;

            return(wrapperException);
        }
 protected void OnInvocationException(ServiceProxyInvokeEventArgs args)
 {
     InvocationException?.Invoke(this, args);
 }