private async Task HandleException(HttpContext context, Exception ex, int httpStatusCode)
        {
            PathString originalPath = context.Request.Path;

            if (_options.ExceptionHandlingPath.HasValue)
            {
                context.Request.Path = _options.ExceptionHandlingPath;
            }

            try
            {
                context.Response.Clear();
                var exceptionHandlerFeature = new ExceptionHandlerFeature()
                {
                    Error = ex,
                    Path  = originalPath.Value,
                };

                context.Features.Set <IExceptionHandlerFeature>(exceptionHandlerFeature);
                context.Features.Set <IExceptionHandlerPathFeature>(exceptionHandlerFeature);
                context.Response.StatusCode = httpStatusCode;
                context.Response.OnStarting(_clearCacheHeadersDelegate, context.Response);

                if (_options.ExceptionHandler != null)
                {
                    await _options.ExceptionHandler(context);
                }

                return;
            }
            finally
            {
                context.Request.Path = originalPath;
            }
        }
Exemplo n.º 2
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                //Log.Error($"There was an unexpected error: {ex.ToString()}");
                //Log.CloseAndFlush();

                PathString originalPath = context.Request.Path;
                if (_options.ExceptionHandlingPath.HasValue)
                {
                    context.Request.Path = _options.ExceptionHandlingPath;
                }

                context.Response.Clear();
                var exceptionHandlerFeature = new ExceptionHandlerFeature()
                {
                    Error = ex,
                    Path  = originalPath.Value,
                };

                context.Features.Set <IExceptionHandlerFeature>(exceptionHandlerFeature);
                context.Features.Set <IExceptionHandlerPathFeature>(exceptionHandlerFeature);
                context.Response.StatusCode = 500;
                context.Response.OnStarting(_clearCacheHeadersDelegate, context.Response);

                await _options.ExceptionHandler(context);

                return;
            }
        }
Exemplo n.º 3
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                WebHelper.LogWebError(_product, _layer, ex, context);

                PathString originalPath = context.Request.Path;
                if (_options.ExceptionHandlingPath.HasValue)
                {
                    context.Request.Path = _options.ExceptionHandlingPath;
                }

                context.Response.Clear();
                var exceptionHandlerFeature = new ExceptionHandlerFeature()
                {
                    Error = ex,
                    Path  = originalPath.Value,
                };

                context.Features.Set <IExceptionHandlerFeature>(exceptionHandlerFeature);
                context.Features.Set <IExceptionHandlerPathFeature>(exceptionHandlerFeature);
                context.Response.StatusCode = 500;
                context.Response.OnStarting(_clearCacheHeadersDelegate, context.Response);

                await _options.ExceptionHandler(context);

                return;
            }
        }
Exemplo n.º 4
0
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(new EventId(1, "UnhandledException"), ex, "An unhandled exception while request");
                // We can't do anything if the response has already started, just abort.
                if (context.Response.HasStarted)
                {
                    _logger.LogError(new EventId(2, "ResponseStartedErrorHandler"), ex, "ResponseStartedErrorHandler");
                    throw;
                }

                PathString originalPath = context.Request.Path;
                if (_options.ExceptionHandlingPath.HasValue)
                {
                    context.Request.Path = _options.ExceptionHandlingPath;
                }
                try
                {
                    context.Response.Clear();
                    var exceptionHandlerFeature = new ExceptionHandlerFeature()
                    {
                        Error = ex,
                        Path  = originalPath.Value,
                    };
                    context.Features.Set <IExceptionHandlerFeature>(exceptionHandlerFeature);
                    context.Features.Set <IExceptionHandlerPathFeature>(exceptionHandlerFeature);
                    context.Response.StatusCode = 500;
                    context.Response.OnStarting(_clearCacheHeadersDelegate, context.Response);

                    await _options.ExceptionHandler(context);

                    if (_diagnosticSource.IsEnabled("Microsoft.AspNetCore.Diagnostics.HandledException"))
                    {
                        _diagnosticSource.Write("Microsoft.AspNetCore.Diagnostics.HandledException", new { httpContext = context, exception = ex });
                    }

                    // TODO: Optional re-throw? We'll re-throw the original exception by default if the error handler throws.
                    return;
                }
                catch (Exception ex2)
                {
                    // Suppress secondary exceptions, re-throw the original.
                    _logger.LogError(new EventId(3, "ErrorHandlerException"), ex, "ErrorHandlerException");
                }
                finally
                {
                    context.Request.Path = originalPath;
                }
                throw; // Re-throw the original if we couldn't handle it
            }
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                bool isWebApi = context.Request.Path.StartsWithSegments("/api") ||
                                context.Request.Path.StartsWithSegments("/internalapi") ||
                                context.Request.Path.StartsWithSegments("/publicapi");

                if (isWebApi)
                {
                    context.Response.StatusCode  = 500;
                    context.Response.ContentType = "application/json";

                    EnvyWebHelper.LogWebError("Core", "Api", ex, context);

                    var errorId      = Activity.Current?.Id ?? context.TraceIdentifier;
                    var jsonResponse = JsonConvert.SerializeObject(new EnvyErrorResponse
                    {
                        ErrorId = errorId,
                        Message = "Some kind of error happened in the API"
                    });
                    await context.Response.WriteAsync(jsonResponse, Encoding.UTF8);
                }
                else
                {
                    EnvyWebHelper.LogWebError(_product, _layer, ex, context);

                    PathString originalPath = context.Request.Path;
                    if (_options.ExceptionHandlingPath.HasValue)
                    {
                        context.Request.Path = _options.ExceptionHandlingPath;
                    }

                    context.Response.Clear();
                    var exceptionHandlerFeature = new ExceptionHandlerFeature()
                    {
                        Error = ex,
                        Path  = originalPath.Value,
                    };

                    context.Features.Set <IExceptionHandlerFeature>(exceptionHandlerFeature);
                    context.Features.Set <IExceptionHandlerPathFeature>(exceptionHandlerFeature);
                    context.Response.StatusCode = 500;
                    context.Response.OnStarting(_clearCacheHeadersDelegate, context.Response);

                    await _options.ExceptionHandler(context);

                    return;
                }
            }
        }
Exemplo n.º 6
0
        public async Task Invoke(HttpContext context, ITmsLogger tmsLogger)
        {
            try
            {
                _tmsLogger = tmsLogger;
                await _next(context);
            }
            catch (Exception ex)
            {
                var infoToLog = new LogDetails()
                {
                    Message   = ex.Message,
                    Product   = "TMS",
                    Location  = context.Request.Path,
                    Hostname  = Environment.MachineName,
                    User      = Environment.UserName,
                    Exception = ex
                };
                _tmsLogger.LogError(infoToLog);

                PathString originalPath = context.Request.Path;

                context.Request.Path = "/Home/Error";

                context.Response.Clear();
                var exceptionHandlerFeature = new ExceptionHandlerFeature()
                {
                    Error = ex,
                    Path  = originalPath.Value,
                };

                context.Features.Set <IExceptionHandlerFeature>(exceptionHandlerFeature);
                context.Features.Set <IExceptionHandlerPathFeature>(exceptionHandlerFeature);
                context.Response.StatusCode = 500;

                await _options.ExceptionHandler(context);

                return;
            }
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _Next(context);

                if (context.Response.StatusCode >= 400)
                {
                    string path = null;
                    if (context.Response.StatusCode == 404)
                    {
                        path = "received for: " + context.Request.Path;
                        _Logger.LogError(0, $"HTTP status code: {context.Response.StatusCode} {path}");
                    }
                    if (!context.Response.HasStarted)
                    {
                        await WriteResponseAsync(context.Response, $"HTTP status code: {context.Response.StatusCode} {path}").ConfigureAwait(true);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError(0, ex, "An unhandled exception has occurred: " + ex.Message);
                // We can't do anything if the response has already started, just abort.
                if (context.Response.HasStarted)
                {
                    _Logger.LogWarning("The response has already started, the error handler will not be executed.");
                    throw;
                }

                PathString originalPath = context.Request.Path;
                if (_Options.ExceptionHandlingPath.HasValue)
                {
                    context.Request.Path = _Options.ExceptionHandlingPath;
                }
                try
                {
                    context.Response.Clear();
                    var exceptionHandlerFeature = new ExceptionHandlerFeature()
                    {
                        Error = ex,
                        Path  = originalPath.Value,
                    };
                    context.Features.Set <IExceptionHandlerFeature>(exceptionHandlerFeature);
                    context.Features.Set <IExceptionHandlerPathFeature>(exceptionHandlerFeature);
                    context.Response.StatusCode = 500;
                    context.Response.OnStarting(_ClearCacheHeadersDelegate, context.Response);

                    await _Options.ExceptionHandler(context);

                    if (_DiagnosticSource.IsEnabled("Microsoft.AspNetCore.Diagnostics.HandledException"))
                    {
                        _DiagnosticSource.Write("Microsoft.AspNetCore.Diagnostics.HandledException", new { httpContext = context, exception = ex });
                    }

                    // TODO: Optional re-throw? We'll re-throw the original exception by default if the error handler throws.
                    return;
                }
                catch (Exception ex2)
                {
                    // Suppress secondary exceptions, re-throw the original.
                    _Logger.LogError(0, ex2, "An exception was thrown attempting to execute the error handler.");
                }
                finally
                {
                    context.Request.Path = originalPath;
                }
                throw; // Re-throw the original if we couldn't handle it
            }
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                // _sw = Stopwatch.StartNew();

                await _next(context);

                // _sw.Stop();

                //LogForContext(context).Information(MessageTemplate, context.Request.Method, context.Request.Path, context.Response?.StatusCode, _sw.ElapsedMilliseconds);
            }
            catch (Exception ex)
            {
                //_sw.Stop();

                var ai = new TelemetryClient();
                ai.TrackException(ex);

                // LogException(context, _sw.ElapsedMilliseconds, ex);

                bool isWebApi = context.Request.Path.StartsWithSegments("/api") ||
                                context.Request.Path.StartsWithSegments("/api-core") ||
                                context.Request.Path.StartsWithSegments("/internalapi") ||
                                context.Request.Path.StartsWithSegments("/publicapi");

                if (isWebApi)
                {
                    context.Response.StatusCode  = 500;
                    context.Response.ContentType = "application/json";

                    var errorId      = context.TraceIdentifier;
                    var jsonResponse = JsonConvert.SerializeObject(new EnvyErrorResponse
                    {
                        ErrorId = errorId,
                        Message = _hostingEnvironment.IsDevelopment() ? ex.ToString() : "Some kind of error happened in the API"
                    });
                    await context.Response.WriteAsync(jsonResponse, Encoding.UTF8);
                }
                else
                {
                    PathString originalPath = context.Request.Path;
                    if (_options.ExceptionHandlingPath.HasValue)
                    {
                        context.Request.Path = _options.ExceptionHandlingPath;
                    }

                    context.Response.Clear();
                    var exceptionHandlerFeature = new ExceptionHandlerFeature()
                    {
                        Error = ex,
                        Path  = originalPath.Value,
                    };

                    context.Features.Set <IExceptionHandlerFeature>(exceptionHandlerFeature);
                    context.Features.Set <IExceptionHandlerPathFeature>(exceptionHandlerFeature);
                    context.Response.StatusCode = 500;
                    context.Response.OnStarting(_clearCacheHeadersDelegate, context.Response);

                    await _options.ExceptionHandler(context);

                    return;
                }
            }
        }