public ApiExceptionMiddleware(ApiExceptionOptions options, RequestDelegate next, ILogger <ApiExceptionMiddleware> logger) { _next = next; _logger = logger; _options = options; }
private Task HandleExceptionAsync(HttpContext context, Exception exception, ApiExceptionOptions opts) { var error = new ApiError { Id = Guid.NewGuid().ToString(), Status = (short)HttpStatusCode.InternalServerError, Title = "Some kind of error occurred in the API. Please use the id and contact our " + "support team if the problem persists." }; opts.AddResponseDetails?.Invoke(context, exception, error); var innerExMessage = GetInnermostExceptionMessage(exception); // _logger.LogError(exception, "BADNESS!!! " + innerExMessage + " -- {ErrorId}.", error.Id); var level = _options.DetermineLogLevel?.Invoke(exception) ?? LogLevel.Error; _logger.Log(level, exception, "BADNESS!!! " + innerExMessage + " -- {ErrorId}.", error.Id); var result = JsonConvert.SerializeObject(error); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(context.Response.WriteAsync(result)); }
public static IApplicationBuilder UseApiExceptionHandler(this IApplicationBuilder builder, Action <ApiExceptionOptions> configureOptions) { var options = new ApiExceptionOptions(); configureOptions(options); return(builder.UseMiddleware <ApiExceptionMiddleware>(options)); }