ajout CustomExceptionFilter

This commit is contained in:
Julien LEICHER 2021-12-14 12:00:47 +01:00
parent c2d1abe808
commit f9eeb453ac
No known key found for this signature in database
GPG Key ID: BE0761B6A007EB96
4 changed files with 52 additions and 2 deletions

View File

@ -1,4 +1,5 @@
using HackerNet.Application;
using HackerNet.Web.Filters;
using HackerNet.Web.Models;
using Microsoft.AspNetCore.Mvc;
@ -22,6 +23,7 @@ public class LinksController : HackerController
}
[HttpGet]
[TypeFilter(typeof(CustomExceptionFilter))]
public IActionResult Detail(Guid id)
{
var link = _linkService.GetLinkDetail(id);

View File

@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace HackerNet.Web.Filters;
public class CustomExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
if (context.Exception is InvalidOperationException)
{
context.Result = new NotFoundResult();
}
}
}

View File

@ -1,6 +1,7 @@
using HackerNet.Application;
using HackerNet.Domain;
using HackerNet.Infrastructure.Repositories.Memory;
using HackerNet.Web.Filters;
var builder = WebApplication.CreateBuilder(args);
@ -15,7 +16,10 @@ builder.Services.AddSingleton<ICommentRepository>(commentsRepository);
builder.Services.AddSingleton<IReadStore>(new MemoryReadStore(linksRepository, commentsRepository));
builder.Services.AddSingleton<LinkService>();
builder.Services.AddControllersWithViews();
builder.Services.AddControllersWithViews(o =>
{
o.Filters.Add<CustomExceptionFilter>();
});
var app = builder.Build();
@ -27,11 +31,40 @@ if (!app.Environment.IsDevelopment())
app.UseHsts();
}
app.Use(async (ctx, next) =>
{
var logger = ctx.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogDebug(">>>>>>>>>>>>>> Début requête");
try
{
await next();
}
catch (Exception e)
{
// Envoi app insights ou autre
logger.LogError(e.Message);
throw e;
}
logger.LogDebug("<<<<<<<<<<<<<< Fin requête");
});
app.Use(async (ctx, next) =>
{
var logger = ctx.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogDebug(">>>>>>>>>>>>>> Début requête 2");
await next();
logger.LogDebug("<<<<<<<<<<<<<< Fin requête 2");
});
app.UseHttpsRedirection();
app.UseStaticFiles();
// app.UseStatusCodePages()
app.UseRouting();
// app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(

View File

@ -1,7 +1,7 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Default": "Debug",
"Microsoft.AspNetCore": "Warning"
}
}