public async Task Invoke(HttpContext context) { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; var ex = context.Features.Get <IExceptionHandlerFeature>()?.Error; if (ex == null) { return; } var isDebugMode = await _appSettingsService.IsDebugMode(); var error = new ApiError { Error = isDebugMode ? ex.ToString() : ex.Message }; using (var writer = new StreamWriter(context.Response.Body)) { _serializer.Serialize(writer, error); await writer.FlushAsync().ConfigureAwait(false); } }