public void FatalError(ExceptionResult exception)
 {
     Color(ConsoleColor.Red, () =>
     {
         inner.FatalError(exception);
     });
 }
    internal static TaskException[] ConvertExceptions(ExceptionResult exception, out string message)
    {
      ExceptionResult current;
      if ((exception.FullTypeName == typeof(TargetInvocationException).FullName) && (exception.InnerExceptionResult != null))
      {
        current = exception.InnerExceptionResult;
      }
      else
      {
        current = exception;
      }

      message = null;
      var exceptions = new List<TaskException>();
      while (current != null)
      {
        if (message == null)
        {
          message = string.Format("{0}: {1}", current.FullTypeName, current.Message);
        }

        exceptions.Add(new TaskException(new SpecException(current)));
        current = current.InnerExceptionResult;
      }

      return exceptions.ToArray();
    }
 public Specification(string name, Result result)
 {
   _status = result.Status;
   _exception = result.Exception;
   _supplements = result.Supplements;
   _name = name;
 }
Beispiel #4
0
        /// <summary>
        /// Method for handling error messages
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            // _logger.LogInformation(await ObtainRequestBody(context.Request));
            // var originalBodyStream = context.Response.Body;
            // await using var responseBody = _recyclableMemoryStreamManager.GetStream();
            // context.Response.Body = responseBody;
            // await _next.Invoke(context);
            // _logger.LogInformation(await ObtainResponseBody(context));
            // await responseBody.CopyToAsync(originalBodyStream);

            string exceptionMessage = context.Exception.Message;
            var    randomCode       = new Random();

            var excResult = new ExceptionResult
            {
                Code    = randomCode.Next(1, 501),
                Message = exceptionMessage
            };

            context.Result = new ContentResult
            {
                Content = JsonSerializer.Serialize(excResult)
            };
            context.ExceptionHandled = true;
        }
Beispiel #5
0
        public override void OnException(ExceptionContext filterContext)
        {
            var writeLog = true;

            if (filterContext.Exception.GetType().ToString() == typeof(FormException).ToString())
            {
                writeLog = ((FormException)filterContext.Exception).WriteLog;
            }

            var customErrors = ((CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors"));

            var exResult = new ExceptionResult
                           (
                filterContext.Exception.Message,
                isWriteLog: writeLog,
                controller: filterContext.Controller.ToString(),
                stackTrace: filterContext.Exception.StackTrace
                           );

            if (customErrors.Mode == CustomErrorsMode.On)
            {
                exResult.ExecuteResult(filterContext);
                filterContext.RequestContext.HttpContext.Response.End();
            }
            else
            {
                base.OnException(filterContext);
            }
        }
Beispiel #6
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            ExceptionResult exceptionResult = null;
            var             responseMessage = await base.SendAsync(request, cancellationToken);

            try
            {
                if (!responseMessage.IsSuccessStatusCode)
                {
                    exceptionResult = responseMessage.Content.ReadAsAsync <ExceptionResult>().Result;
                    if (exceptionResult == null)
                    {
                        exceptionResult = new ExceptionResult();
                    }
                    exceptionResult.HttpStatusCode = responseMessage.StatusCode;
                    responseMessage = responseMessage.EnsureSuccessStatusCode();
                }
            }
            catch (HttpRequestException hrEx)
            {
                throw new XOMNIPublicAPIException(exceptionResult, hrEx);
            }

            return(responseMessage);
        }
Beispiel #7
0
        public void HandleAsync_IfIsTopLevelCatchBlockAndCanCreateExceptionResult_InitializesResult(bool includeDetail)
        {
            Mock <IExceptionHandler> mock   = new Mock <IExceptionHandler>(MockBehavior.Strict);
            IHttpActionResult        result = null;

            mock
            .Setup(h => h.HandleAsync(It.IsAny <ExceptionHandlerContext>(), It.IsAny <CancellationToken>()))
            .Returns <ExceptionHandlerContext, CancellationToken>((c, i) =>
            {
                result = c != null ? c.Result : null;
                return(Task.FromResult(0));
            });
            IExceptionHandler innerHander = mock.Object;

            IExceptionHandler product = CreateProductUnderTest(innerHander);

            Exception          expectedException         = CreateDummyException();
            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();

            using (HttpConfiguration configuration = CreateConfiguration())
                using (HttpRequestMessage expectedRequest = CreateRequest())
                {
                    configuration.Services.Replace(typeof(IContentNegotiator), expectedContentNegotiator);
                    configuration.Formatters.Clear();
                    MediaTypeFormatter expectedFormatter = CreateDummyFormatter();
                    configuration.Formatters.Add(expectedFormatter);

                    ExceptionHandlerContext context = new ExceptionHandlerContext(new ExceptionContext
                    {
                        Exception      = expectedException,
                        CatchBlock     = CreateTopLevelCatchBlock(),
                        RequestContext = new HttpRequestContext
                        {
                            Configuration      = configuration,
                            IncludeErrorDetail = includeDetail
                        },
                        Request = expectedRequest
                    });

                    CancellationToken cancellationToken = CancellationToken.None;

                    // Act
                    Task task = product.HandleAsync(context, cancellationToken);

                    // Assert
                    Assert.NotNull(task);
                    task.WaitUntilCompleted();
                    Assert.Equal(TaskStatus.RanToCompletion, task.Status);

                    Assert.IsType <ExceptionResult>(result);
                    ExceptionResult exceptionResult = (ExceptionResult)result;
                    Assert.Same(expectedException, exceptionResult.Exception);
                    Assert.Equal(includeDetail, exceptionResult.IncludeErrorDetail);
                    Assert.Same(expectedContentNegotiator, exceptionResult.ContentNegotiator);
                    Assert.Same(expectedRequest, exceptionResult.Request);
                    Assert.NotNull(exceptionResult.Formatters);
                    Assert.Equal(1, exceptionResult.Formatters.Count());
                    Assert.Same(expectedFormatter, exceptionResult.Formatters.Single());
                }
        }
        public void OnFatalError(ExceptionResult exception)
        {
            string message;

            _server.TaskExplain(_contextTask, "Fatal error: " + exception.Message);
            _server.TaskException(_contextTask, ExceptionResultConverter.ConvertExceptions(exception, out message));
            _server.TaskFinished(_contextTask, message, TaskResult.Exception);
        }
Beispiel #9
0
 public Specification(string leader, string name, Result result)
 {
     _leader      = leader;
     _status      = result.Status;
     _exception   = result.Exception;
     _supplements = result.Supplements;
     _name        = name;
 }
        public void OnFatalError(ExceptionResult exceptionResult)
        {
            _server.TaskOutput(_context.AssemblyTask, "Fatal error: " + exceptionResult.Message, TaskOutputType.STDOUT);
            _server.TaskException(_context.AssemblyTask, GetExceptions(exceptionResult));
            _server.TaskFinished(_context.AssemblyTask, GetExceptionMessage(exceptionResult), TaskResult.Exception);

            _errors += 1;
        }
        public void ExceptionResultTestConstructorWithStatusCode(int statusCode)
        {
            var sut = new ExceptionResult(_errorMessage, _traceId, _correlationId, statusCode);

            sut.CorrelationId.Should().Be(_correlationId);
            sut.Message.Should().Be(_errorMessage);
            sut.StatusCode.Should().Be(statusCode);
            sut.TraceId.Should().Be(_traceId);
        }
Beispiel #12
0
        public void OnFatalError(ExceptionResult exception)
        {
            _failureOccurred = true;
            _console.WriteLine("");
            _console.WriteLine("Fatal Error");
            _console.WriteLine(exception.ToString());

            _summary.RecordFatalError(exception);
        }
Beispiel #13
0
 public void OnFatalError(ExceptionResult exception)
 {
     if (this.currentRunStats != null)
     {
         this.currentRunStats.Stop();
         this.currentRunStats = null;
     }
     this.SendErrorMessage(Strings.RUNERROR);
 }
        public void OnFatalError(ExceptionResult exception)
        {
            if (this.currentRunStats != null)
            {
                this.currentRunStats.Stop();
                this.currentRunStats = null;
            }

            this.frameworkHandle.SendMessage(TestMessageLevel.Error, "Machine Specifications Visual Studio Test Adapter - Fatal error while executing test." + Environment.NewLine + exception.ToString());
        }
Beispiel #15
0
        public void OnFatalError(ExceptionResult exception)
        {
            if (this.currentRunStats != null)
            {
                this.currentRunStats.Stop();
                this.currentRunStats = null;
            }

            this.frameworkHandle.SendMessage(TestMessageLevel.Error, Strings.RUNERROR + Environment.NewLine + exception.ToString());
        }
Beispiel #16
0
 private static ExceptionResult CreateExceptionResult(ExceptionResult result, string error)
 {
     if (result == null)
     {
         result = new ExceptionResult();
     }
     result.ErrorCode    = -1;
     result.ErrorMessage = error;
     return(result);
 }
Beispiel #17
0
        public void OnFatalError(ExceptionResult exception)
        {
            string message;

            _server.TaskOutput(_runAssemblyTask, "Fatal error: " + exception.Message, TaskOutputType.STDOUT);
            _server.TaskException(_runAssemblyTask, ExceptionResultConverter.ConvertExceptions(exception, out message));
            _server.TaskFinished(_runAssemblyTask, message, TaskResult.Exception);

            _errors += 1;
        }
        Gallio.Common.Diagnostics.ExceptionData Convert(ExceptionResult result)
        {
            if (result == null)
            {
                return(null);
            }

            Gallio.Common.Diagnostics.ExceptionData inner = Convert(result.InnerExceptionResult);
            return(new Gallio.Common.Diagnostics.ExceptionData(result.TypeName, result.Message, result.StackTrace, new PropertySet(), inner));
        }
Beispiel #19
0
        public void Does_Save_Person_Store_Items_Fail()
        {
            //Local variables.
            RecordsController controller = new RecordsController();

            //Conduct Test Experiment.
            ExceptionResult result = (ExceptionResult)controller.SavePerson(null);

            //Make sure we got a success result back.
            Assert.IsTrue(result.Exception != null);
        }
        public void IsValidationExceptionReturnedWhentheIsValidatedValueIsFalse()
        {
            ValidationResult = Validate32BitInteger.Validate("200%");

            if (ValidationResult.IsValidated == false)
            {
                ExceptionResult = Validate32BitInteger.GetException(ValidationResult.ExceptionId);
            }

            Assert.IsNotNull(ExceptionResult);
        }
Beispiel #21
0
        public IActionResult GetValidRecords(string operationId, [FromQuery] int page = 0, [FromQuery] int batchSize = 50)
        {
            var getAttempt = _productManager.GetValidRecords(operationId, page, batchSize);

            if (!getAttempt.Success)
            {
                return(ExceptionResult.Create(getAttempt.Exception));
            }

            return(Ok(getAttempt.Result));
        }
        public void IsExceptionResultClassCreated()
        {
            ValidationResult = Validate32BitInteger.Validate("E200");

            if (ValidationResult.IsValidated == false)
            {
                ExceptionResult = Validate32BitInteger.GetException(ValidationResult.ExceptionId);
            }

            Assert.NotNull(ExceptionResult);
        }
Beispiel #23
0
        public void ExceptionResult_NoError()
        {
            // Verify that an exception result with no error doesn't rethrow.

            var er = new ExceptionResult();

            Assert.Null(er.ExceptionType);
            Assert.Null(er.ExceptionMessage);

            er.ThrowOnError();
        }
Beispiel #24
0
        public void Is_Names_Sorted_Fail()
        {
            //Local variables.
            RecordsController controller = new RecordsController();

            //Conduct Test Experiment.
            ExceptionResult result = (ExceptionResult)controller.GetNames();

            //Determine Test Results

            //Make sure we got a success result back.
            Assert.IsTrue(result.Exception != null);
        }
        public void ExceptionResultToStringTest()
        {
            var sut    = new ExceptionResult(_errorMessage, _traceId, _correlationId);
            var asJson = sut.ToString();

            JsonSerializerSettings settings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver  = new CamelCasePropertyNamesContractResolver()
            };

            sut.Should().BeEquivalentTo(JsonConvert.DeserializeObject <ExceptionResult>(asJson, settings));
        }
        private void onExceptionResult(ExceptionResult excptionResult)
        {
            TaskCompletionSource <SuccessResult> answer;

            if (_answers.TryDequeue(out answer))
            {
                answer.SetException(new RequestExecutionException(excptionResult.exceptionMessage));
            }
            else
            {
                throw new Exception("Result without Request");
            }
        }
Beispiel #27
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            OpenTracing.ITracer tracer = SignalFxTracer;
            using var scope = tracer.BuildSpan("HttpTrigger").StartActive();

            string name = req.Query["name"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            name ??= data?.name;

            scope.Span.SetTag("span.kind", "server");
            scope.Span.SetTag("query.name", name ?? "<null>");
            scope.Span.SetTag("http.method", req.Method);

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            ObjectResult result = null;

            try
            {
                if (name == "crash")
                {
                    // The SampleServer is not running, this will fail and will create a span if the
                    // error information.
                    var samplerServerUrl = $"http://localhost:19999{SampleServer.RequestPath}/";
                    var client           = new SampleClientLibrary(samplerServerUrl);
                    responseMessage = await client.RequestAsync(responseMessage, CancellationToken.None);
                }

                result = new OkObjectResult(responseMessage);
            }
            catch (Exception e)
            {
                result = new ExceptionResult(e, includeErrorDetail: true);
                scope.Span.SetTag("error.message", e.Message);
                throw;
            }
            finally
            {
                scope.Span.SetTag("http.status_code", result?.StatusCode ?? 500);
                scope.Span.SetTag("error", true);
            }

            return(result);
        }
Beispiel #28
0
        private async Task VerifyResponse(string resultMessage = DEFAULTERRORMESSAGE, int statusCode = DEFAULTERRORCODE)
        {
            _httpContext.Response.ContentType.Should().Be("application/json");

            var expected = new ExceptionResult(resultMessage, _traceId, _correlationId, statusCode).ToString();

            _httpContext.Response.Body.Position = 0;
            using (StreamReader streamReader = new StreamReader(_httpContext.Response.Body))
            {
                string actual = await streamReader.ReadToEndAsync().ConfigureAwait(false);

                expected.Should().Be(actual);
            }
        }
        private static IEnumerable <ExceptionResult> Flatten(this ExceptionResult result)
        {
            var exception = result;

            if (exception.FullTypeName == typeof(TargetInvocationException).FullName && exception.InnerExceptionResult != null)
            {
                exception = exception.InnerExceptionResult;
            }

            for (var current = exception; current != null; current = current.InnerExceptionResult)
            {
                yield return(current);
            }
        }
        public void ExceptionOfT_Invoke_ReturnNewExceptionResultOfT()
        {
            // Arrange:
            var sample = new ExceptionResult <object>
            {
                InnerException = new Exception(),
            };

            // Act:
            var result = Result.Exception <object>(sample.InnerException);

            // Assert:
            result.Should().BeOfType <ExceptionResult <object> >()
            .And.BeEquivalentTo(sample);
        }
        public void DoesExceptionResultHaveExceptionIdValue()
        {
            int ExpectedExceptionResultId = 0;
            int ExceptionResultId         = -1;

            ValidationResult = Validate32BitInteger.Validate("200%73501");

            if (ValidationResult.IsValidated == false)
            {
                ExceptionResult   = Validate32BitInteger.GetException(ValidationResult.ExceptionId);
                ExceptionResultId = ExceptionResult.ExceptionId;
            }

            Assert.AreEqual(ExpectedExceptionResultId, ExceptionResultId);
        }
Beispiel #32
0
        public void RecordException(Exception ex)
        {
            var result = new ExceptionResult(ex, FailureSite.Test);

            SetResult(result.ResultState, result.Message, result.StackTrace);

            if (AssertionResults.Count > 0 && result.ResultState == ResultState.Error)
            {
                // Add pending failures to the legacy result message
                Message += Environment.NewLine + Environment.NewLine + CreateLegacyFailureMessage();

                // Add to the list of assertion errors, so that newer runners will see it
                AssertionResults.Add(new AssertionResult(AssertionStatus.Error, result.Message, result.StackTrace));
            }
        }
Beispiel #33
0
        private bool ValidateTextboxText
            (string TextboxText)
        {
            bool TextboxValidationValue = true;

            IntegerValidationResult = Validate32BitInteger.Validate(TextboxText);
            TextboxValidationValue  = IntegerValidationResult.IsValidated;

            if (TextboxValidationValue == false)
            {
                ExceptionResult = Validate32BitInteger.GetException(IntegerValidationResult.ExceptionId);
            }

            return(TextboxValidationValue);
        }
        public void FatalError(ExceptionResult exception)
        {
//            _console.WriteLine(exception.ToString());
            EmptyLine();
        }
 public void OnFatalError(ExceptionResult exception)
 {
   _writer.WriteError(exception.Message, exception.StackTrace);
   _failureOccured = true;
 }
 public void OnFatalError(ExceptionResult exception)
 {
 }
 public static Result CreateResultObject(string command)
 {
     Result result = null;
         switch (command) {
             case "attach":
                 result = new AttachResult();
                 break;
             case "detach":
                 result = new DetachResult();
                 break;
             case "getthreads":
                 result = new ThreadsResult();
                 break;
             case "appdomains":
                 result = new AppDomainsResult();
                 break;
             case "assemblies":
                 result = new AssembliesResult();
                 break;
             case "callstack":
                 result = new CallStackResult();
                 break;
             case "setbreakpoint":
                 result = new BreakPointResult();
                 break;
             case "exception":
                 result = new ExceptionResult();
                 break;
             case "go":
                 result = new GoResult();
                 break;
             case "assemblyloadevent":
                 result = new AssemblyLoadResult();
                 break;
             case "removebreakpoint":
                 result = new RemoveBreakPointResult();
                 break;
             case "arguments":
                 result = new ArgumentsResult();
                 break;
             case "members":
                 result = new MembersResult();
                 break;
             case "value":
                 result = new MemberValueResult();
                 break;
         }
         return result;
 }
 public SpecException(ExceptionResult exceptionResult) : base(exceptionResult.Message)
 {
   _exceptionResult = exceptionResult;
 }
    public void OnFatalError(ExceptionResult exception)
    {
      string message;
      _server.TaskExplain(_runAssemblyTask, "Fatal error: " + exception.Message);
      _server.TaskException(_runAssemblyTask, ExceptionResultConverter.ConvertExceptions(exception, out message));
      _server.TaskFinished(_runAssemblyTask, message, TaskResult.Exception);

      _errors += 1;
    }
 public void OnFatalError(ExceptionResult exception)
 {
   LastFatalError = exception;
 }
 public void OnFatalError(ExceptionResult exception)
 {
   FailureOccured = true;
   _console.WriteLine("Fatal Error");
   _console.WriteLine(exception.ToString());
 }
 public void OnFatalError(ExceptionResult exception)
 {
     write.FatalError(exception);
 }
        public void OnFatalError(ExceptionResult exception)
        {
            var root = new XElement("listener", new XElement("onfatalerror", exception.ToXml()));

            SendMessage(root);
        }
 public void OnFatalError(ExceptionResult exception)
 {
     testListener.WriteLine("Fatal error: " + exception, Category.Error);
 }
        public void OnFatalError(ExceptionResult exception)
        {
            var root = new XElement("listener", new XElement("onfatalerror", exception.ToXml()));

            this._listener.SyncProcessMessage(new RemoteListenerMessage(root));
        }
 public void OnFatalError(ExceptionResult exception)
 {
     _outputAction("Fatal Error\r\n" + exception.Message);
 }
 public void OnFatalError(ExceptionResult exception)
 {
   _listeners.ForEach(listener => listener.OnFatalError(exception));
 }
 public override void OnFatalError(ExceptionResult exception)
 {
   _listener.OnFatalError(exception);
 }
 public void OnFatalError(ExceptionResult exception)
 {
   _writer.WriteError(exception.Message, exception.ToString());
   _failureOccurred = true;
 }
    Gallio.Common.Diagnostics.ExceptionData Convert(ExceptionResult result)
    {
      if (result == null) 
        return null;

      Gallio.Common.Diagnostics.ExceptionData inner = Convert(result.InnerExceptionResult);
      return new Gallio.Common.Diagnostics.ExceptionData(result.TypeName, result.Message, result.StackTrace, new PropertySet(), inner);
    }
    static void RenderError(XmlWriter reportBuilder, ExceptionResult exception)
    {
      if (exception == null)
      {
        return;
      }

      reportBuilder.WriteStartElement("error");
      
      reportBuilder.WriteStartElement("message");
      reportBuilder.WriteCData(exception.Message);
      reportBuilder.WriteEndElement();
      
      reportBuilder.WriteStartElement("stack-trace");
      reportBuilder.WriteCData(exception.StackTrace);
      reportBuilder.WriteEndElement();

      reportBuilder.WriteEndElement();
    }
 public void OnFatalError(ExceptionResult exception)
 {
   _server.TaskExplain(_contextTask, "Fatal error: " + exception.Exception.Message);
   _server.TaskException(_contextTask, new[] { new TaskException(exception.Exception) });
   _server.TaskFinished(_contextTask, null, TaskResult.Exception);
 }
        void UpdateTestFailed(SpecificationInfo specification, long executionTime, ExceptionResult exceptionResult = null)
        {
            _writer(string.Format("\x1B[31m* {0} (FAILED)\x1B[39m", specification.Name)); // red

            string errorMessage = null;
            string errorStackTrace = null;
            if (exceptionResult != null)
            {
                errorMessage = exceptionResult.Message;
                errorStackTrace = exceptionResult.ToString();
            }

            _apiClient.UpdateTest(GetSpecificationName(specification),
                                  FrameworkName,
                                  _currentAssembly.Name,
                                  "Failed",
                                  executionTime,
                                  errorMessage,
                                  errorStackTrace,
                                  specification.CapturedOutput,
                                  null);
        }
 public override void OnFatalError(ExceptionResult exception)
 {
     _failureOccurred = true;
 }