Skip to content

Commit

Permalink
Include app crash error in serilog logs
Browse files Browse the repository at this point in the history
  • Loading branch information
PatTheHyruler committed Sep 28, 2024
1 parent 8cd385f commit f4eb717
Showing 1 changed file with 80 additions and 61 deletions.
141 changes: 80 additions & 61 deletions WebApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,89 +122,108 @@

// Configure the HTTP request pipeline.

if (!app.Environment.IsDevelopment() || true)
try
{
await using var scope = app.Services.CreateAsyncScope();
await scope.ServiceProvider.MigrateDbAsync<AppDbContext>();
}
if (!app.Environment.IsDevelopment() || true)
{
await using var scope = app.Services.CreateAsyncScope();
await scope.ServiceProvider.MigrateDbAsync<AppDbContext>();
}

app.SeedIdentity();
app.SetupYouTube();
app.SeedIdentity();
app.SetupYouTube();

app.UseHttpsRedirection();
app.UseHttpsRedirection();

app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), apiApp =>
{
apiApp.UseExceptionHandler(apiBuilder =>
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), apiApp =>
{
apiBuilder.Run(async context =>
apiApp.UseExceptionHandler(apiBuilder =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(new ErrorResponseDto
apiBuilder.Run(async context =>
{
ErrorType = EErrorType.GenericError,
Message = "Something went wrong",
}, JsonUtils.DefaultJsonSerializerOptions);
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(new ErrorResponseDto
{
ErrorType = EErrorType.GenericError,
Message = "Something went wrong",
}, JsonUtils.DefaultJsonSerializerOptions);
});
});
});
});
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
if (app.Environment.IsDevelopment())
{
var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
foreach (var description in provider.ApiVersionDescriptions)
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName);
}
var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
foreach (var description in provider.ApiVersionDescriptions)
{
options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName);
}
});
}

var imagesDirectory = app.Services.GetRequiredService<AppPaths>().GetImagesDirectoryAbsolute();
var imagesDirectoryPath = Path.Combine(app.Environment.ContentRootPath, imagesDirectory);
Directory.CreateDirectory(imagesDirectoryPath);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(imagesDirectoryPath),
RequestPath = "/images",
});
}

var imagesDirectory = app.Services.GetRequiredService<AppPaths>().GetImagesDirectoryAbsolute();
var imagesDirectoryPath = Path.Combine(app.Environment.ContentRootPath, imagesDirectory);
Directory.CreateDirectory(imagesDirectoryPath);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(imagesDirectoryPath),
RequestPath = "/images",
});
app.UseStaticFiles();

app.UseStaticFiles();
string[] specialPaths = ["/api", "/hangfire"];
bool IsSpecialPath(string path) => specialPaths.Any(path.StartsWith);

string[] specialPaths = ["/api", "/hangfire"];
bool IsSpecialPath(string path) => specialPaths.Any(path.StartsWith);
var spaIndexPath = Path.Combine(app.Environment.ContentRootPath, spaDirectory, "index.html");
if (Path.Exists(spaIndexPath))
{
app.MapWhen(c => !IsSpecialPath(c.Request.Path.Value ?? ""),
spaAppBuilder =>
{
spaAppBuilder.UseSpaStaticFiles();
spaAppBuilder.UseSpa(_ => { });
});
}

var spaIndexPath = Path.Combine(app.Environment.ContentRootPath, spaDirectory, "index.html");
if (Path.Exists(spaIndexPath))
{
app.MapWhen(c => !IsSpecialPath(c.Request.Path.Value ?? ""),
spaAppBuilder =>
{
spaAppBuilder.UseSpaStaticFiles();
spaAppBuilder.UseSpa(_ => { });
});
}
app.UseRouting();

app.UseRouting();
app.UseCors(corsAllowAllName);
app.UseCors(corsAllowCredentialsName);

app.UseCors(corsAllowAllName);
app.UseCors(corsAllowCredentialsName);
app.UseAuthentication();
app.UseAuthorization();

app.UseAuthentication();
app.UseAuthorization();
app.UseHangfireDashboard(options: new DashboardOptions
{
AppPath = null,
DarkModeEnabled = true,
Authorization = app.Services.GetRequiredService<IEnumerable<IDashboardAuthorizationFilter>>(),
AsyncAuthorization = app.Services.GetRequiredService<IEnumerable<IDashboardAsyncAuthorizationFilter>>(),
});

app.UseHangfireDashboard(options: new DashboardOptions
{
AppPath = null,
DarkModeEnabled = true,
Authorization = app.Services.GetRequiredService<IEnumerable<IDashboardAuthorizationFilter>>(),
AsyncAuthorization = app.Services.GetRequiredService<IEnumerable<IDashboardAsyncAuthorizationFilter>>(),
});
app.MapControllers();

app.MapControllers();
app.Run();
}
catch (Exception e)
{
try
{
await using var scope = app.Services.CreateAsyncScope();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(e, "An error occured while running the application.");
await Log.CloseAndFlushAsync();
}
catch (Exception logException)
{
await Console.Error.WriteLineAsync($"Failed to log catchall application error {logException.GetType()}: {logException.Message}");
}
throw;
}

app.Run();
return;

string GetHangfireConnectionString(WebApplicationBuilder webApplicationBuilder)
Expand Down

0 comments on commit f4eb717

Please sign in to comment.