예제 #1
0
        /// <summary>
        /// Combine properties from exception Data dictionary and Azure Functions filter context properties
        /// </summary>
#pragma warning disable CS0618 // Type or member is obsolete
        private static IList <Item> Data(FunctionExceptionContext exceptionContext)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            var data          = new List <Item>();
            var exceptionData = exceptionContext.Exception?.ToDataList();

            if (exceptionData?.Count > 0)
            {
                data.AddRange(exceptionData);
            }

            foreach (var property in exceptionContext.Properties.Where(p => !string.IsNullOrWhiteSpace(p.Key) && p.Key != Constants.StopwatchKeyName))
            {
                data.Add(new Item {
                    Key = property.Key, Value = property.Value?.ToString()
                });
            }

            data.Add(new Item {
                Key = nameof(exceptionContext.FunctionInstanceId), Value = exceptionContext.FunctionInstanceId.ToString()
            });
            data.Add(new Item {
                Key = nameof(exceptionContext.FunctionName), Value = exceptionContext.FunctionName
            });

            return(data);
        }
예제 #2
0
        public override Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
        {
            var telemetry = new TelemetryClient
            {
                InstrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY")
            };

            var time = DateTime.Now;
            var sw   = Stopwatch.StartNew();

            telemetry.Context.Operation.Id = Guid.NewGuid().ToString();

            exceptionContext.Logger.LogError(
                $"Function Exception: '{exceptionContext.FunctionName}" +
                $":{exceptionContext.FunctionInstanceId}" +
                $"Inner Exception: {exceptionContext.Exception.InnerException}" +
                $"Message Exception: {exceptionContext.Exception.Message}");

            telemetry.TrackRequest(this.Name, time, sw.Elapsed, HttpStatusCode.InternalServerError.ToString(), false);

            exceptionContext.Logger.LogError($"Encerrada {this.Name}: {DateTime.Now}");
            telemetry.TrackTrace($"Encerrada {this.Name}: {DateTime.Now}");

            return(Task.CompletedTask);
        }
예제 #3
0
        public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
        {
            Throw.IfNull(exceptionContext, nameof(exceptionContext));

            RemoveScope(exceptionContext.FunctionInstanceId);
            return(Task.CompletedTask);
        }
예제 #4
0
 public async Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
 {
     if (exceptionContext.Exception.InnerException is TwitterBotBusinessException)
     {
         var erroredHashtags = (exceptionContext.Exception.InnerException as TwitterBotBusinessException).Hashtags;
         await ProcessErroredHashtags(erroredHashtags);
     }
 }
예제 #5
0
        public override Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
        {
            // custom error handling logic could be written here
            // (e.g. write a queue message, send a notification, etc.)
            exceptionContext.Logger.LogError($"ErrorHandler called. Function '{exceptionContext.FunctionName}:{exceptionContext.FunctionInstanceId} failed.");

            return(Task.CompletedTask);
        }
예제 #6
0
        public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
        {
            var logger = exceptionContext.Logger;

            logger.LogInformation($"Error in {exceptionContext.FunctionName} with instanceId {exceptionContext.FunctionInstanceId}");
            logger.LogInformation(exceptionContext.Exception.ToString());
            return(Task.CompletedTask);
        }
예제 #7
0
        public static async Task Ship(FunctionExceptionContext exceptionContext, HttpContext context, ElmahIoFunctionOptions options)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            var exception     = exceptionContext.Exception;
            var baseException = exception?.GetBaseException();
            var createMessage = new CreateMessage
            {
                DateTime        = DateTime.UtcNow,
                Detail          = Detail(exception),
                Type            = baseException?.GetType().FullName,
                Title           = baseException.Message,
                Data            = Data(exceptionContext),
                Cookies         = Cookies(context),
                Form            = Form(context),
                Hostname        = Hostname(context),
                ServerVariables = ServerVariables(context),
                StatusCode      = StatusCode(exception, context),
                Url             = context?.Request?.Path.Value,
                QueryString     = QueryString(context),
                Method          = context?.Request?.Method,
                Severity        = Severity(exception, context),
                Source          = Source(baseException),
                Application     = options.Application,
            };

            if (options.OnFilter != null && options.OnFilter(createMessage))
            {
                return;
            }

            if (elmahIoClient == null)
            {
                elmahIoClient = ElmahioAPI.Create(options.ApiKey, new ElmahIoOptions
                {
                    Timeout   = options.Timeout,
                    UserAgent = UserAgent(),
                });

                elmahIoClient.Messages.OnMessage += (sender, args) =>
                {
                    options.OnMessage?.Invoke(args.Message);
                };
                elmahIoClient.Messages.OnMessageFail += (sender, args) =>
                {
                    options.OnError?.Invoke(args.Message, args.Error);
                };
            }

            try
            {
                await elmahIoClient.Messages.CreateAndNotifyAsync(options.LogId, createMessage);
            }
            catch (Exception e)
            {
                options.OnError?.Invoke(createMessage, e);
                // If there's a Exception while generating the error page, re-throw the original exception.
            }
        }
        public void OnExceptionAsync_WithFunctionExceptionContextAsNull_ThrowsArgumentNullException()
        {
            // arrange
            FunctionExceptionContext functionExceptionContext = null;
            CancellationToken        cancellationToken        = new CancellationToken();

            // act & assert
            Assert.ThrowsAsync <ArgumentNullException>(() => new ScopeCleanupFilter().OnExceptionAsync(functionExceptionContext, cancellationToken));
        }
예제 #9
0
 public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
 {
     if (exceptionContext.Exception is UnauthorizedAccessException)
     {
         logger.LogError(exceptionContext.Exception, exceptionContext.Exception.Message);
         var r = new UnauthorizedResult();
         httpContextAccessor.HttpContext.Response.StatusCode = r.StatusCode;
     }
     return(Task.CompletedTask);
 }
예제 #10
0
        public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
        {
            if (exceptionContext == null)
            {
                throw new ArgumentNullException(nameof(exceptionContext));
            }

            RemoveScope(exceptionContext.FunctionInstanceId);
            return(Task.CompletedTask);
        }
        public override Task OnExceptionAsync(FunctionExceptionContext exceptionContext,
                                              CancellationToken cancellationToken)
        {
            var state = new Dictionary <string, object>
            {
                { FunctionInstanceId, exceptionContext.FunctionInstanceId },
                { FunctionName, exceptionContext.FunctionName }
            };

            exceptionContext.Logger.Log(LogLevel.Error, 0, state, exceptionContext.Exception, Formatter);
            return(Task.CompletedTask);
        }
 public async Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
 {
     if (exceptionContext.Exception.InnerException != null && exceptionContext.Exception.InnerException is AuthorizationException)
     {
         _httpContextAccessor.HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
         await _httpContextAccessor.HttpContext.Response.WriteAsync(exceptionContext.Exception.InnerException.Message);
     }
     if (exceptionContext.Exception.InnerException != null && exceptionContext.Exception.InnerException is ArgumentNullException)
     {
         _httpContextAccessor.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
         await _httpContextAccessor.HttpContext.Response.WriteAsync(exceptionContext.Exception.InnerException.Message);
     }
 }
예제 #13
0
        public override Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
        {
            var exception = exceptionContext.Exception;

            do
            {
                exceptionContext.Logger.LogError(exception,
                                                 $"{exceptionContext.FunctionName}:{exceptionContext.FunctionInstanceId} failed with exception: {exception}");

                exception = exception.InnerException;
            } while (exception != null);

            return(Task.CompletedTask);
        }
        public override Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
        {
            var time = DateTime.Now;
            var sw   = Stopwatch.StartNew();

            exceptionContext.Logger.LogError(
                $"ErrorHandler called." +
                $"\nFunction: '{exceptionContext.FunctionName}:{exceptionContext.FunctionInstanceId}" +
                $"\nMessage: {exceptionContext.Exception.Message}" +
                $"\nInner Exception: {exceptionContext.Exception.InnerException}");

            exceptionContext.Logger.LogError($"{exceptionContext.FunctionName} ended with exception: {DateTime.Now}");

            return(Task.CompletedTask);
        }
예제 #15
0
        /// <summary>
        /// This method is called by Azure Functions when a function throws an uncaught exception. It is not intended to be called manually.
        /// </summary>
#pragma warning disable CS0618 // Type or member is obsolete
        public async Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            HttpContext httpContext = null;

            foreach (var argument in exceptionContext.Properties.Keys.ToList())
            {
                switch (exceptionContext.Properties[argument])
                {
                case HttpRequest request:
                    httpContext = request.HttpContext;
                    exceptionContext.Properties.Remove(argument);
                    break;
                }
            }

            await MessageShipper.Ship(exceptionContext, httpContext, options);
        }
            public override Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
            {
                exceptionContext.Logger.LogInformation("ExceptionFilter_" + _id);
                Act("ExceptionFilter_" + _id);

                if (_throwAtPhase != "ctor")
                {
                    // verify that the property added by the invocation filter
                    // is available to all filters
                    var value = exceptionContext.Properties["TestProperty"];
                    Assert.Equal("TestValue", value);
                }

                Assert.NotNull(exceptionContext.Exception);
                Assert.NotNull(exceptionContext.ExceptionDispatchInfo);
                Assert.NotNull(exceptionContext.Logger);

                return(Task.CompletedTask);
            }
예제 #17
0
        public async Task ExceptionFilterAttribute_ExceptionTestAsync()
        {
            var mockKey = "29d342d1-8d08-44fc-a8bc-2ac3e25af903";

            Environment.SetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", mockKey);

            var exceptionFilter = new ExceptionFilterAttribute();

            var exceptionContext = new FunctionExceptionContext(
                functionInstanceId: Guid.NewGuid(),
                functionName: "FunctionMock",
                logger: _loggerMock.Object,
                exceptionDispatchInfo: ExceptionDispatchInfo.Capture(new Exception("MockException")),
                properties: new Dictionary <string, object>());

            await exceptionFilter.OnExceptionAsync(exceptionContext, new CancellationToken());

            Assert.NotNull(exceptionFilter);
        }
예제 #18
0
// Types 'FunctionExceptionContext' and 'IFunctionFilter' (and other Filter-related types) are marked as preview/obsolete,
// but the guidance from the Azure Functions team is to use it, so we disable the warning.
#pragma warning disable CS0618
        public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancelControl)
#pragma warning restore CS0618
        {
            // A few lines which we need for attaching a debugger during development.
            // @ToDo: Remove before shipping.
            Console.WriteLine($"Filter Entry Point: {nameof(FunctionInvocationManagementFilter)}.{nameof(OnExceptionAsync)}(..).");
            Console.WriteLine($"FunctionInstanceId: {Format.SpellIfNull(exceptionContext?.FunctionInstanceId)}.");
            Process proc = Process.GetCurrentProcess();

            Console.WriteLine($"Process name: \"{proc.ProcessName}\", Process Id: \"{proc.Id}\".");
            // --

            // Get error:
            Exception error = exceptionContext?.Exception
                              ?? new Exception("OnExceptionAsync(..) is invoked, but no Exception information is available. ");

            OnPostFunctionError(exceptionContext, error, nameof(OnExceptionAsync));

            return(Task.CompletedTask);
        }
        public override Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
        {
            var telemetry = new TelemetryClient
            {
                InstrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY")
            };

            telemetry.Context.Operation.Id = Guid.NewGuid().ToString();
            telemetry.TrackException(exceptionContext.Exception);

            exceptionContext.Logger.LogError(
                $"Function Exception: '{exceptionContext.FunctionName}" +
                $":{exceptionContext.FunctionInstanceId}" +
                $"Inner Exception: {exceptionContext.Exception.InnerException}" +
                $"Message Exception: {exceptionContext.Exception.Message}");

            exceptionContext.Logger.LogError($"Encerrada {Name}: {DateTime.Now}");
            telemetry.TrackTrace($"Encerrada {Name}: {DateTime.Now}");

            return(Task.CompletedTask);
        }
예제 #20
0
 public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
 {
     exceptionContext.Logger.LogInformation($"Executing {nameof(OnExceptionAsync)} in filter {nameof(ErrorHandlingFilter)}");
     return(Task.CompletedTask);
 }
 public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
 {
     exceptionContext.Logger.LogError($"Something went wrong while executing {exceptionContext.FunctionName}. Exception details: {exceptionContext.Exception}");
     return(Task.CompletedTask);
 }
예제 #22
0
 public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
 {
     return(Task.CompletedTask);
 }
예제 #23
0
 public override Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
 {
     exceptionContext.Logger.LogError($"ErrorHandler called. Function '{exceptionContext.FunctionName}:{exceptionContext.FunctionInstanceId} failed.");
     return(Task.CompletedTask);
 }
예제 #24
0
 public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
 {
     _log.LogError($"Exception raised by the application {exceptionContext.Exception.ToString()}");
     return(Task.CompletedTask);
 }
 public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
 {
     RemoveScope(exceptionContext.FunctionInstanceId);
     return(Task.CompletedTask);
 }
 public Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
 {
     Act("ExceptionFilter_Instance");
     return(Task.CompletedTask);
 }