Example #1
0
        private static void ReadErrorHandler(XmlNode node, IRewriterConfiguration config)
        {
            var code = node.GetRequiredAttribute(Constants.AttrCode);

            XmlNode typeNode = node.Attributes[Constants.AttrType];
            XmlNode urlNode  = node.Attributes[Constants.AttrUrl];

            if (typeNode == null && urlNode == null)
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrUrl), node);
            }

            IRewriteErrorHandler handler;

            if (typeNode != null)
            {
                // <error-handler code="500" url="/oops.aspx" />
                handler = TypeHelper.Activate(typeNode.Value, null) as IRewriteErrorHandler;
                if (handler == null)
                {
                    throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.InvalidTypeSpecified, typeNode.Value, typeof(IRewriteErrorHandler)), node);
                }
            }
            else
            {
                handler = new DefaultErrorHandler(urlNode.Value);
            }

            if (!int.TryParse(code, out var statusCode))
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.InvalidHttpStatusCode, code), node);
            }

            config.ErrorHandlers.Add(statusCode, handler);
        }
Example #2
0
        public static Optimizely NewDefaultInstance(string sdkKey, string fallback)
        {
            var logger             = OptimizelyLogger ?? new DefaultLogger();
            var errorHandler       = new DefaultErrorHandler();
            var eventDispatcher    = new DefaultEventDispatcher(logger);
            var builder            = new HttpProjectConfigManager.Builder();
            var notificationCenter = new NotificationCenter();

            var configManager = builder
                                .WithSdkKey(sdkKey)
                                .WithDatafile(fallback)
                                .WithLogger(logger)
                                .WithErrorHandler(errorHandler)
                                .WithNotificationCenter(notificationCenter)
                                .Build(true);

            EventProcessor eventProcessor = null;

#if !NETSTANDARD1_6 && !NET35
            eventProcessor = new BatchEventProcessor.Builder()
                             .WithLogger(logger)
                             .WithMaxBatchSize(MaxEventBatchSize)
                             .WithFlushInterval(MaxEventFlushInterval)
                             .WithEventDispatcher(eventDispatcher)
                             .WithNotificationCenter(notificationCenter)
                             .Build();
#endif

            return(NewDefaultInstance(configManager, notificationCenter, eventDispatcher, errorHandler, logger, eventProcessor: eventProcessor));
        }
        private static void ReadErrorHandler(XmlNode node, RewriterConfiguration config)
        {
            XmlNode codeNode = node.Attributes[Constants.AttrCode];

            if (codeNode == null)
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrCode), node);
            }

            XmlNode typeNode = node.Attributes[Constants.AttrType];
            XmlNode urlNode  = node.Attributes[Constants.AttrUrl];

            if (typeNode == null && urlNode == null)
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrUrl), node);
            }

            IRewriteErrorHandler handler = null;

            if (typeNode != null)
            {
                // <error-handler code="500" url="/oops.aspx" />
                handler = TypeHelper.Activate(typeNode.Value, null) as IRewriteErrorHandler;
                if (handler == null)
                {
                    throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.InvalidTypeSpecified));
                }
            }
            else
            {
                handler = new DefaultErrorHandler(urlNode.Value);
            }

            config.ErrorHandlers.Add(Convert.ToInt32(codeNode.Value), handler);
        }
        public async Task GraphQL_Error()
        {
            // arrange
            var errorHandler = new DefaultErrorHandler(
                Array.Empty <IErrorFilter>(),
                new RequestExecutorOptions());

            var middleware = new ExceptionMiddleware(
                context => throw new GraphQLException("Something is wrong."),
                errorHandler);

            var request = QueryRequestBuilder.New()
                          .SetQuery("{ a }")
                          .SetQueryName("a")
                          .Create();

            var requestContext = new Mock <IRequestContext>();

            requestContext.SetupProperty(t => t.Result);

            // act
            await middleware.InvokeAsync(requestContext.Object);

            // assert
            requestContext.Object.Result.ToJson().MatchSnapshot();
        }
        public static Optimizely NewDefaultInstance()
        {
            var logger = OptimizelyLogger ?? new DefaultLogger();
            OptimizelySDKConfigSection OptlySDKConfigSection = null;

            try
            {
                OptlySDKConfigSection = ConfigurationManager.GetSection(ConfigSectionName) as OptimizelySDKConfigSection;
            }
            catch (ConfigurationErrorsException ex)
            {
                logger.Log(LogLevel.ERROR, "Invalid App.Config. Unable to initialize optimizely instance" + ex.Message);
                return(null);
            }

            HttpProjectConfigElement httpProjectConfigElement = OptlySDKConfigSection.HttpProjectConfig;

            if (httpProjectConfigElement == null)
            {
                return(null);
            }

            var errorHandler       = new DefaultErrorHandler(logger, false);
            var eventDispatcher    = new DefaultEventDispatcher(logger);
            var builder            = new HttpProjectConfigManager.Builder();
            var notificationCenter = new NotificationCenter();
            var configManager      = builder
                                     .WithSdkKey(httpProjectConfigElement.SDKKey)
                                     .WithUrl(httpProjectConfigElement.Url)
                                     .WithFormat(httpProjectConfigElement.Format)
                                     .WithPollingInterval(TimeSpan.FromMilliseconds(httpProjectConfigElement.PollingInterval))
                                     .WithBlockingTimeoutPeriod(TimeSpan.FromMilliseconds(httpProjectConfigElement.BlockingTimeOutPeriod))
#if !NET40 && !NET35
                                     .WithAccessToken(httpProjectConfigElement.DatafileAccessToken)
#endif
                                     .WithLogger(logger)
                                     .WithErrorHandler(errorHandler)
                                     .WithNotificationCenter(notificationCenter)
                                     .Build(true);

            EventProcessor eventProcessor = null;

            var batchEventProcessorElement = OptlySDKConfigSection.BatchEventProcessor;

            if (batchEventProcessorElement == null)
            {
                return(null);
            }

            eventProcessor = new BatchEventProcessor.Builder()
                             .WithMaxBatchSize(batchEventProcessorElement.BatchSize)
                             .WithFlushInterval(TimeSpan.FromMilliseconds(batchEventProcessorElement.FlushInterval))
                             .WithTimeoutInterval(TimeSpan.FromMilliseconds(batchEventProcessorElement.TimeoutInterval))
                             .WithLogger(logger)
                             .WithEventDispatcher(eventDispatcher)
                             .WithNotificationCenter(notificationCenter)
                             .Build();

            return(NewDefaultInstance(configManager, notificationCenter, eventDispatcher, errorHandler, logger, eventProcessor: eventProcessor));
        }
    /// <inheritdoc/>
    public IChromelyResource HandleError(Stream?stream, Exception?exception = null)
    {
        var  info       = DefaultErrorHandler.GetFileInfo(stream);
        bool fileExists = info.Item1;
        int  fileSize   = info.Item2;

        return(DefaultErrorHandler.HandleResourceError(fileExists, fileSize, exception));
    }
    /// <inheritdoc/>
    public virtual IChromelyResource HandleError(FileInfo?fileInfo, Exception?exception = null)
    {
        var  info       = DefaultErrorHandler.GetFileInfo(fileInfo);
        bool fileExists = info.Item1;
        int  fileSize   = info.Item2;

        var resource = DefaultErrorHandler.HandleResourceError(fileExists, fileSize, exception);

        Logger.Instance.Log.LogWarning("File: {fileInfo?.FullName}: {resource?.StatusText}", fileInfo?.FullName, resource?.StatusText);
        return(resource);
    }
Example #8
0
        public static void Main()
        {
            Application         app          = new Application();
            DefaultErrorHandler errorHandler = new DefaultErrorHandler();
            DebugLogger         logger       = new DebugLogger();

            using (Runtime runtime = new Runtime(logger, errorHandler))
            {
                MainWindow window = new MainWindow(runtime);
                app.Run(window);
            }
        }
Example #9
0
        /// <summary>
        /// Creates new Twino MVC
        /// </summary>
        public TwinoMvc()
        {
            Routes            = new List <RouteLeaf>();
            Services          = new ServiceContainer();
            RouteFinder       = new RouteFinder();
            ControllerFactory = new ControllerFactory();
            NotFoundResult    = StatusCodeResult.NotFound();
            ErrorHandler      = new DefaultErrorHandler();
            Policies          = new PolicyContainer();

            AppBuilder = new MvcAppBuilder(this);
        }
        // ReSharper disable once AsyncVoidMethod
        public static async void FireAndForget(this Task task, IErrorHandler handler = default)
        {
            try
            {
                await task.WithoutChangingContext();
            }
            catch (Exception ex)
            {
                if (handler.IsNullOrDefault())
                {
                    handler = new DefaultErrorHandler();
                }

                handler?.HandleError(ex);
            }
        }
        public void TestErrorHandlerMessage()
        {
            DefaultErrorHandler = new DefaultErrorHandler(LoggerMock.Object, false);
            string testingException = "Testing exception";

            try
            {
                throw new OptimizelyException("Testing exception");
            }
            catch (OptimizelyException ex)
            {
                DefaultErrorHandler.HandleError(ex);
            }

            LoggerMock.Verify(log => log.Log(LogLevel.ERROR, testingException), Times.Once);
        }
Example #12
0
        internal async void HandleException(Exception e, object m)
        {
            ErrorAdvice advice = null;

            try
            {
                foreach (ErrorAdvice adv in AdviceChain)
                {
                    if (adv.GetExceptionType() == e.GetType())
                    {
                        advice = adv;
                    }
                }
                //var advice = (from adv in ErrorAdvice where adv.GetExceptionType() == e.GetType() select adv).FirstOrDefault();
                //if nothing in advice chain matches use default error handler
                if (advice == null)
                {
                    DefaultErrorHandler.HandleError(e, m);
                    return;
                }

                if (advice.RetryOnFail)
                {
                    //need to determine type of retry
                    //var retryAdvice = advice as ITimedRetryAdvice;
                    if (advice.AdviceType == AdviceType.TimedRetry)
                    {
                        var errorCount = 0;
                        _errorDictionary.TryGetValue(m, out errorCount);
                        if (errorCount == 0)
                        {
                            _errorDictionary.Add(m, 0);
                        }
                        else if (errorCount >= advice.RetryCount)
                        {
                            SendToDeadLetterQueue(m.ToString());
                            return;
                        }
                        Log.Warn("TimedRetryAdvice found for message " + m + ", retrying Handle Message");
                        _errorDictionary[m] = errorCount + 1;
                        await Task.Delay((advice.RetryInterval * 1000));

                        HandleMessage(m.ToString());

                        return;
                    }
                    //var retryRequeueAdvice = advice as IRetryRequeueAdvice;
                    if (advice.AdviceType == AdviceType.RetryRequeue)
                    {
                        Log.Warn("RetryRequeue Advice found for message " + m + ", requeing message");
                        SendToMessageQueue(m.ToString());
                        return;
                    }
                }
                //just in case measure
                DefaultErrorHandler.HandleError(e, m);
            }
            catch (Exception ex)
            {
                Log.Error("Error handling exception for" + m.ToString() + ": " + ex.Message);
                DefaultErrorHandler.HandleError(ex, m);
            }
        }
Example #13
0
        public void OnRequest()
        {
            var handler = new DefaultErrorHandler();

            using (Application.OverrideIoc()) {
                var logManagerMock = Substitute.For <LogManager>();
                var config         = new WebsiteConfig()
                {
                    Extra = new Dictionary <string, object>()
                };
                var configManagerMock = Substitute.For <WebsiteConfigManager>();
                configManagerMock.WebsiteConfig.Returns(config);
                Application.Ioc.Unregister <LogManager>();
                Application.Ioc.RegisterInstance(logManagerMock);
                Application.Ioc.Unregister <WebsiteConfigManager>();
                Application.Ioc.RegisterInstance(configManagerMock);
                // Only return message if error occurs with ajax request
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    request.headers["X-Requested-With"] = "XMLHttpRequest";
                    handler.OnError(new ArgumentException("some message"));
                    Assert.Equals(response.GetContentsFromBody(), "some message");
                }
                // Display status and message if the error is HttpException
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    handler.OnError(new HttpException(404, "wrong address"));
                    var contents = response.GetContentsFromBody();
                    Assert.IsTrueWith(
                        contents.Contains("404 wrong address") && !contents.Contains("<pre>"), contents);
                }
                // Display full exception dependent on website configuration
                config.Extra[ExtraConfigKeys.DisplayFullExceptionForRequest] = true;
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    handler.OnError(new ArgumentException("500 some error"));
                    var contents = response.GetContentsFromBody();
                    Assert.IsTrueWith(
                        contents.Contains("500 some error") && contents.Contains("<pre>"), contents);
                }
                config.Extra[ExtraConfigKeys.DisplayFullExceptionForRequest] = false;
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    handler.OnError(new ArgumentException("500 some error"));
                    var contents = response.GetContentsFromBody();
                    Assert.IsTrueWith(
                        contents.Contains("500 some error") && !contents.Contains("<pre>"), contents);
                }
                // Test error logging
                logManagerMock.ClearReceivedCalls();
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    handler.OnError(new HttpException(401, "user error"));
                    logManagerMock.DidNotReceiveWithAnyArgs().LogError(null);
                }
                logManagerMock.ClearReceivedCalls();
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    handler.OnError(new HttpException(500, "server error"));
                    logManagerMock.ReceivedWithAnyArgs().LogError(null);
                }
            }
        }
Example #14
0
 public Dispatcher()
 {
     ErrorHandler = new DefaultErrorHandler <T>();
     WfExecutionPlan.CallStack = new List <bool>();
 }
Example #15
0
        public ExceptionInfo(Exception exception, IErrorHandler errorHandler)
        {
            if (exception == null)
            {
                throw new NullParameterException(typeof(ExceptionInfo), "ctor", "exception");
            }
            if (errorHandler == null)
            {
                errorHandler = new DefaultErrorHandler();
            }

            // Type

            Type type = exception.GetType();

            _type = new ClassInfo(type.FullName, type.Assembly.FullName);

            // HelpLink

            try
            {
                _helpLink = exception.HelpLink;
            }
            catch (Exception ex)
            {
                _helpLink = string.Format(ExceptionFormatString, ex.GetType().FullName);
            }

            // Replace LF with CRLF in every property that is likely to have new lines, so that it displays
            // properly in a multi-line textbox.

            // Message

            try
            {
                if (exception is UserException)
                {
                    _message = TextUtil.ReplaceLfWithCrlf(errorHandler.FormatErrorMessage((UserException)exception));
                }
                else
                {
                    _message = TextUtil.ReplaceLfWithCrlf(exception.Message);
                }
            }
            catch (Exception ex)
            {
                _message = string.Format(ExceptionFormatString, ex.GetType().FullName);
            }

            // Source

            try
            {
                _source = exception.Source;
            }
            catch (Exception ex)
            {
                _source = string.Format(ExceptionFormatString, ex.GetType().FullName);
            }

            // StackTrace

            try
            {
                // The stack trace may be null if the exception is not actually thrown (just instantiated).
                // SqlException also has a bug that loses the stack trace when deserializing.

                _stackTrace = TextUtil.ReplaceLfWithCrlf(exception.StackTrace);
            }
            catch (Exception ex)
            {
                _stackTrace = string.Format(ExceptionFormatString, ex.GetType().FullName);
            }

            // TargetSite

            try
            {
                _targetSite = (exception.TargetSite == null ? null : exception.TargetSite.ToString());
            }
            catch (Exception ex)
            {
                _targetSite = string.Format(ExceptionFormatString, ex.GetType().FullName);
            }

            // HResult

            try
            {
                PropertyInfo propertyHr = exception.GetType().GetProperty("HResult",
                                                                          BindingFlags.NonPublic | BindingFlags.Instance);
                object tempValue = propertyHr.GetValue(exception, null);
                _hResult = (tempValue == null ? null : string.Format("0x{0:x}", tempValue));
            }
            catch (Exception ex)
            {
                _hResult = string.Format(ExceptionFormatString, ex.GetType().FullName);
            }

            // Other properties

            InitialiseAdditionalProperties(exception);

            // ToString()

            InitialiseToString(exception);

            // InnerException

            _innerException = (exception.InnerException == null ? null : new ExceptionInfo(exception.InnerException, errorHandler));
        }