/// <summary> /// /// </summary> /// <param name="feature"></param> /// <param name="model"></param> /// <returns></returns> protected override bool CustomError(IExceptionHandlerFeature feature, ErrorModel model) { if (feature.Error is System.Security.Cryptography.CryptographicException) { if (feature.Error.Source == "Microsoft.AspNetCore.DataProtection") { foreach (var cookiesKey in Request.Cookies.Keys) { Response.Cookies.Delete(cookiesKey); } model.Exception = new LoginException("登录超时!", feature.Error); return(true); } } else if (feature.Error is WxException exception) { model.Code = exception.ErrorCode; model.Exception = exception; if (!exception.Header.IsNull()) { foreach (var kv in exception.Header) { Response.Headers.Add(kv.Key, kv.Value); } } return(true); } return(base.CustomError(feature, model)); }
private async static Task CheckAccessAsync(HttpContext context) { context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; context.Response.ContentType = "text/html"; IExceptionHandlerFeature exceptionHandler = context.Features.Get <IExceptionHandlerFeature>(); if (exceptionHandler != null) { Exception ex = exceptionHandler.Error; if (ex is TokenExpiredException || ex is TokenInvalidException || ex is WrongPasswordException) { context.Response.StatusCode = 401; await context.Response.WriteAsync("Acesso negado."); } else if (ex is UnauthorizedException) { context.Response.StatusCode = 403; await context.Response.WriteAsync("Acesso negado."); } else { context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; string message = JsonConvert.SerializeObject(new { message = ex.Message, stack = ex.StackTrace }); await context.Response.WriteAsync(message, System.Text.Encoding.UTF8); } } }
private static async void ReservationGlobalExceptionHandler(IExceptionHandlerFeature ex, HttpContext context) { ReservationGlobalException exception = (ReservationGlobalException)ex.Error; var logger = _loggerFactory.CreateLogger($"{exception.ErrorCode} - GlobalExceptionHandler"); logger.LogError(context.User.Identity.Name, GetLogMessage(new List <Exception> { exception })); List <ReservationErrorMessage> detailErrorList = GetExceptionErrors(exception.ExceptionList); RequestResultViewModel result = new RequestResultViewModel { Data = null, ErrorCode = exception.ErrorCode, ErrorMessage = exception.UserMessage, DetailErrorList = detailErrorList }; var serializerSetting = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var jsonResult = JsonConvert.SerializeObject(result, serializerSetting); context.Response.StatusCode = 501; await context.Response.WriteAsync(jsonResult); }
public ErrorModule() { Get("/error", (req, res) => { throw new Exception("oops baby .. !!!!"); }); Get("/errorhandler", async(req, res) => { string error = string.Empty; IExceptionHandlerFeature feature = req.HttpContext.Features.Get <IExceptionHandlerFeature>(); if (feature != null) { if (feature.Error is ArgumentNullException) { res.StatusCode = 402; } error = feature.Error.ToString(); } await res.WriteAsync($"There has been an error {error} .. !!!!"); }); }
private static async Task WriteResponse(HttpContext httpContext, ILogger logger, bool includeDetails) { // Try and retrieve the error from the ExceptionHandler middleware IExceptionHandlerFeature exceptionHandlerFeature = httpContext.Features.Get <IExceptionHandlerFeature>(); Exception unhandledException = exceptionHandlerFeature?.Error; // Should always exist, but best to be safe! if (unhandledException == null) { return; } ProblemDetails problemDetails = ConvertToProblemDetails(unhandledException, includeDetails); // ProblemDetails has it's own content type httpContext.Response.ContentType = ProblemDetailContentType; httpContext.Response.StatusCode = problemDetails.Status ?? (int)HttpStatusCode.InternalServerError; // The exception is first logged by the Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware class, // then by this method, but it's worth it since the second time the exception is logged, we end up with // the errorId accompanying the logged stack trace. // Whenever the web API responds with a ProblemDetails instance, the user has the opportunity to report // this issue and hopefully, he will mention the 'errorId', thus easing the job of the developer // assigned to fix it. logger.LogError(unhandledException, "An unhandled exception has been caught; its associated id is: {ErrorId}", problemDetails.Extensions[ErrorId]); // Since the ProblemDetails instance is always serialized as JSON, the web API will not be able to // correctly handle 'Accept' HTTP header. // @satrapu April 1st 2020: Find a way to use ASP.NET Core content negotiation to serialize // the ProblemDetails instance in the format expected by the client. await JsonSerializer.SerializeAsync(httpContext.Response.Body, problemDetails); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. // app.UseHsts(); app.UseExceptionHandler(builder => { builder.Run(async ctx => { ctx.Response.StatusCode = (int)HttpStatusCode.InternalServerError; IExceptionHandlerFeature error = ctx.Features.Get <IExceptionHandlerFeature>(); if (error != null) { ctx.Response.AddApplicationError(error.Error.Message); string result = JsonConvert.SerializeObject(new { error = error.Error.Message }); await ctx.Response.WriteAsync(result); } }); }); } // app.UseHttpsRedirection(); app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); app.UseAuthentication(); app.UseMvc(); }
public static void UseCustomException(this IApplicationBuilder app) //Public ve static olmak zorunda { app.UseExceptionHandler(configure => { configure.Run(async context => { context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; IExceptionHandlerFeature error = context.Features.Get <IExceptionHandlerFeature>(); //Burada hatayi yakaladik if (error != null) { Exception ex = error.Error; ErrorDto errorDto = new ErrorDto(); errorDto.Status = 500; errorDto.Errors.Add("Id bilgisi bulunamamistir."); errorDto.Errors .Add(ex.Message); //Kendi donus Dto umuza firlatilan hatalari ekledik. hatayi sen elle yazamazsin. Cunki Message set degil. /*Burada List den gelen Add metodunu kullaniyoruz. */ await context.Response.WriteAsync( JsonConvert.SerializeObject(errorDto)); //Donusu Json olarak yaptik /* * Bu kisim Put metodu icin hazirlanmistir. */ } }); }); }
private static Task WriteGeneralExceptionResponseAsync( HttpContext context, bool isDevelopment, IExceptionHandlerFeature exceptionFeature, Guid exceptionId, IHttpConnectionFeature connection) { var routeData = context.GetRouteData() ?? new RouteData(); var actionContext = new ActionContext(context, routeData, new ActionDescriptor()); var result = new ObjectResult(new ProblemDetails { Detail = isDevelopment ? exceptionFeature.Error.StackTrace : "Check logs with the provided traceId", Title = "Error processing the request", Status = (int)HttpStatusCode.InternalServerError, Extensions = { { "traceId", exceptionId.ToString() }, { "connectionId", connection.ConnectionId }, }, }) { StatusCode = (int)HttpStatusCode.InternalServerError, }; var executor = context.RequestServices .GetRequiredService <IActionResultExecutor <ObjectResult> >(); return(executor.ExecuteAsync(actionContext, result)); }
private static async Task ServerInternal(HttpContext context, IExceptionHandlerFeature exception, IWebHostEnvironment env) { string error = string.Empty; if (env.IsDevelopment()) { error = JsonConvert.SerializeObject(new { errors = exception.Error.Message, stackTrace = exception.Error.StackTrace, }); } else { error = JsonConvert.SerializeObject(new { errors = "Something when wrong please contact with administrator thanks", }); } context.Response.StatusCode = 500; context.Response.ContentType = CONTENT_TYPE; await context.Response.WriteAsync(error).ConfigureAwait(false); }
public IActionResult Error() { IExceptionHandlerFeature context = HttpContext.Features.Get <IExceptionHandlerFeature>(); IActionResult result; string logMessage = "Unexpected exception caught"; switch (context.Error) { case ValidationException error: logMessage = null; result = ValidationProblem(new ValidationProblemDetails( error.Errors.ToDictionary(failure => failure.PropertyName, failure => new[] { failure.ErrorMessage }))); break; default: result = _environment.IsDevelopment() ? Problem(context.Error.StackTrace, title: context.Error.Message) : Problem(); break; } if (!string.IsNullOrEmpty(logMessage)) { _logger.LogError(context.Error, logMessage); } return(result); }
public Error Create(IExceptionHandlerFeature contextFeature) { Error error = contextFeature.Error switch { NotFoundException notFoundException => notFoundException.Errors == null ? new NotFoundError(notFoundException.Message) : new NotFoundError(notFoundException.Message, new ErrorDetailsCollection(notFoundException.Errors)), UnauthorizedAccessException unauthorizedAccessException => new UnauthorizedAccessError(unauthorizedAccessException.Message), AppException appException => new AppError(appException.Message, new ErrorDetailsCollection(appException.Errors)), DomainException domainException => new DomainError(domainException.Message, new ErrorDetailsCollection(domainException.Errors)), _ => new InternalServerError(contextFeature.Error.Message) }; return(error); } }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } initializeContainer(app); container.Verify(); // Middleware to enable parsing of culture header app.UseRequestLocalization(); // Middleware to handle exceptions, which cannot be catched in controller app.UseExceptionHandler(appError => { appError.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; IExceptionHandlerFeature contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature != null) { await context.Response.WriteAsync(JsonConvert.SerializeObject(contextFeature.Error.Message)); } }); }); string[] allowedOrigins = Configuration.GetSection("AllowedOrigins").Get <string[]>(); if (allowedOrigins == null) { allowedOrigins = new string[] { "http://localhost:8088", "http://localhost:4200", "http://localhost:6768" }; } app.UseCors(options => options .WithOrigins(allowedOrigins) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); app.UseMvc(); // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui, specifying the Swagger JSON endpoint string prefix = Configuration.GetSection("RoutePrefix").Get <string>(); app.UseSwaggerUI(c => { c.SwaggerEndpoint(prefix + "/swagger/v1/swagger.json", "OCG Data Service V1"); // To serve the Swagger UI at the app's root, set the RoutePrefix property to an empty string c.RoutePrefix = string.Empty; }); }
public static string GetInstance(this IExceptionHandlerFeature feature) { return(feature switch { ExceptionHandlerFeature e => e.Path, _ => "unknown" });
public IActionResult Error() { IExceptionHandlerFeature x = HttpContext.Features.Get <IExceptionHandlerFeature>(); if (x != null) { try { ViewData["path"] = ((ExceptionHandlerFeature)x).Path; } catch { ViewData["path"] = "Unknown"; } if (x.Error != null) { ViewData["message"] = x.Error.Message; ViewData["stacktrace"] = x.Error.StackTrace; } } else { ViewData["message"] = "I died."; } var y = View(); return(View()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseExceptionHandler(config => { config.Run(async context => { IExceptionHandlerFeature exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>(); if (exceptionHandlerFeature != null) { ILogger logger = loggerFactory.CreateLogger("Global exception logger"); logger.LogError(500, exceptionHandlerFeature.Error, exceptionHandlerFeature.Error.Message); } context.Response.StatusCode = 500; await context.Response.WriteAsync("Exception: " + exceptionHandlerFeature.Error.Message); }); }); app.UseMvc(); }
public BadRequestProblemDetails(ArgumentOutOfRangeException ex, IExceptionHandlerFeature errorFeature, HttpContext context) : base(StatusCodes.Status400BadRequest) { const string detail = "One or more arguments are out of range"; SetCommonBadRequestProblemDetails(errorFeature, context, detail, ex.Message); }
private static void ConfigureExceptionHandling(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(subApp => { subApp.Run(async context => { IExceptionHandlerFeature exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>(); if (exceptionHandlerFeature != null) { ILogger logger = loggerFactory.CreateLogger("Global exception logger"); logger.LogError(500, exceptionHandlerFeature.Error, exceptionHandlerFeature.Error.Message); } context.Response.StatusCode = 500; await context.Response.WriteAsync("An unexpected fault happened. Try again later."); }); }); } }
public BadRequestProblemDetails(InvalidOperationException ex, IExceptionHandlerFeature errorFeature, HttpContext context) : base(StatusCodes.Status400BadRequest) { const string detail = "The requested operation is invalid"; SetCommonBadRequestProblemDetails(errorFeature, context, detail, ex.Message); }
/// <summary> /// Adds the default exception handling logic that will display a developer exception page in develop and a short message during deployment /// </summary> public static IApplicationBuilder UseOmexExceptionHandler(this IApplicationBuilder builder, IHostEnvironment environment) { if (environment.IsDevelopment()) { builder.UseDeveloperExceptionPage(); } else { builder.UseExceptionHandler(appError => { appError.Run(context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; IExceptionHandlerFeature contextFeature = context.Features.Get <IExceptionHandlerFeature>(); Dictionary <string, string> errorDict = new Dictionary <string, string> { { "Message", "Internal Server Error" }, { "ErrorMessage", contextFeature?.Error?.Message ?? string.Empty }, { "RequestId", Activity.Current?.Id ?? context.TraceIdentifier }, { "Suggestion", "For local debugging, set ASPNETCORE_ENVIRONMENT environment variable to 'Development' and restart the application" } }; return(context.Response.WriteAsync(JsonSerializer.Serialize(errorDict))); }); }); } return(builder); }
private void SetCommonBadRequestProblemDetails(IExceptionHandlerFeature errorFeature, HttpContext context, string detail, params string[] errorMessages) { Detail = detail; Instance = errorFeature.GetInstance(); Extensions.TryAdd("errors", errorMessages); Extensions.TryAdd("traceId", Activity.Current?.Id ?? context.TraceIdentifier); }
public static void ConfigureExceptionHandler(this IApplicationBuilder app) { app.UseExceptionHandler(appError => { appError.Run(async context => { IExceptionHandlerFeature contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature?.Error != null) { int statusCode = StatusCodes.Status409Conflict; string result = String.Empty; TodoErrorResponse errorModel = null; if (contextFeature.Error is TODOCustomError customException) { errorModel = new TodoErrorResponse(customException.ResponseStatusCode, customException.ErrorMessage); statusCode = customException.ResponseStatusCode; } else { errorModel = new TodoErrorResponse(statusCode, contextFeature.Error.Message); } context.Response.StatusCode = statusCode; context.Response.ContentType = "application/json"; result = JsonConvert.SerializeObject(errorModel, new StringEnumConverter()); await context.Response.WriteAsync(result).ConfigureAwait(false); } }); }); }
public static void ConfigureExceptionHandler(this IApplicationBuilder app) { app.UseExceptionHandler(appError => { appError.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; IExceptionHandlerFeature contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature != null) { Exception error = contextFeature.Error; string message = DefaultErrorMessage; if (error is ArgumentException argumentException) { message = argumentException.Message; } var errorMsg = new ErrorModelInfo() { Message = message, ErrorObject = error.Message, StatusCode = context.Response.StatusCode, }; await context.Response.WriteAsync(errorMsg.ToString()); } }); }); }
void HandleGlobalException(IApplicationBuilder app) { app.Run(async context => { context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; IExceptionHandlerFeature exceptionHandler = context.Features.Get <IExceptionHandlerFeature>(); if (exceptionHandler != null) { switch (exceptionHandler.Error) { case HttpException error: context.Response.StatusCode = (int)error.StatusCode; await context.Response.WriteAsync(JsonConvert.SerializeObject(error.ToResponse())); break; default: await context.Response.WriteAsync(JsonConvert.SerializeObject(new ExceptionResponse { ["message"] = exceptionHandler.Error.Message })); break; } //logger.LogError($"Something went wrong: {contextFeature.Error}"); } }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // Global Exception Handler app.UseExceptionHandler(builder => { builder.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; IExceptionHandlerFeature exceptionHandler = context.Features.Get <IExceptionHandlerFeature>(); if (exceptionHandler != null) { context.Response.AddErrorHeaders(exceptionHandler.Error.Message); await context.Response.WriteAsync(exceptionHandler.Error.Message); } }); }); //app.UseHttpsRedirection(); } app.UseRouting(); app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); //app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseExceptionHandler(builder => { builder.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.Headers.Add("access-control-Allow-Origin", "*"); IExceptionHandlerFeature error = context.Features.Get <IExceptionHandlerFeature>(); if (error != null) { context.Response.AddApplicationError(error.Error.Message); await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false); } }); }); // app.UseHttpsRedirection(); app.UseAuthentication(); app.UseStaticFiles(); app.UseMvc(); app.UseCors("AllowOrigin"); }
private static void HandleError(IApplicationBuilder builder) { if (Exceptions.Any(p => p.Value.Any())) { builder.Run( async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "text/html"; IExceptionHandlerFeature error = context.Features.Get <IExceptionHandlerFeature>(); if (error != null) { await context.Response.WriteAsync($"<h1>Error: {error.Error.Message}</h1>").ConfigureAwait(false); } StringBuilder errorDetails = new StringBuilder(); foreach (KeyValuePair <string, List <Exception> > ex in Exceptions) { foreach (Exception val in ex.Value) { errorDetails.Append($"<h2>Error on {ex.Key}: {val.Message}</h2>"); errorDetails.Append($"<h3>Further details: {val.StackTrace}</h3>"); } } await context.Response.WriteAsync(errorDetails.ToString()).ConfigureAwait(false); KraftLogger.LogError(errorDetails.ToString()); }); return; } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seed seeder) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(builder => { builder.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; IExceptionHandlerFeature error = context.Features.Get <IExceptionHandlerFeature>(); if (error != null) { context.Response.AddApplicationError(error.Error.Message); await context.Response.WriteAsync(error.Error.Message); } }); }); } //app.UseHttpsRedirection(); //seeder.SeedUsers(); app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); app.UseAuthentication(); app.UseMvc(); }
public bool SendErrorEmailSync(IExceptionHandlerFeature exception) { try { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress(_emailFrom, _emailFrom)); emailMessage.To.Add(new MailboxAddress(_emailTo, _emailTo)); emailMessage.Subject = $"{_environment} - {_appName} - {exception.Error.Message}"; emailMessage.Body = new TextPart("plain") { Text = exception.Error.StackTrace }; using (var client = new SmtpClient()) { client.Connect(_smtpHost, _smtpPort); client.Send(emailMessage); client.Disconnect(true, CancellationToken.None); } return(true); } catch (Exception) { return(false); } }
public Error Error() { IExceptionHandlerFeature errorFeature = HttpContext.Features.Get <IExceptionHandlerFeature>(); Exception exception = errorFeature.Error; return(new Error(500, exception.Message)); }
public static IApplicationBuilder UseDefaultExceptionDelegate([NotNull] this IApplicationBuilder thisValue, Func <HttpContext, Exception, ILogger, Task> onError, ILogger logger = null) { onError ??= async(context, exception, log) => { log?.LogError(exception, exception.Message); context.Response.ContentType = "text/html"; await context.Response.WriteAsync(new ResponseStatus { StatusCode = (HttpStatusCode)context.Response.StatusCode, Exception = exception }.ToString() .Replace(Environment.NewLine, $"{Environment.NewLine}<br />")); }; thisValue.UseExceptionHandler(app => { app.Run(async context => { IExceptionHandlerFeature contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature == null) { return; } await onError(context, contextFeature.Error, logger); }); }); return(thisValue); }