Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;

namespace Project.Api.Infrastructure;

public sealed class ConcurrencyExceptionFilter : IExceptionFilter
{
private readonly ILogger<ConcurrencyExceptionFilter> _logger;
public ConcurrencyExceptionFilter(ILogger<ConcurrencyExceptionFilter> logger) => _logger = logger;

public void OnException(ExceptionContext context)
{
if (context.Exception is DbUpdateConcurrencyException ex)
{
_logger.LogWarning(ex, "Optimistic concurrency conflict detected.");

var problem = new ConcurrencyProblemDetails(
"The resource changed since you last fetched it. Fetch the latest version and try again.");

context.Result = new ObjectResult(problem) { StatusCode = problem.Status };
context.ExceptionHandled = true; // prevent default 500
}
}
}
//try commit again
//more comments
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Microsoft.AspNetCore.Mvc;

namespace Project.Api.Infrastructure;

public sealed class ConcurrencyProblemDetails : ProblemDetails
{
public ConcurrencyProblemDetails(string? detail = null)
{
var x = 4;

Check warning on line 9 in Project.App/Project.Api/Infrastructure/ConcurrencyProblemDetails.cs

View workflow job for this annotation

GitHub Actions / backend

The variable 'x' is assigned but its value is never used

Check warning on line 9 in Project.App/Project.Api/Infrastructure/ConcurrencyProblemDetails.cs

View workflow job for this annotation

GitHub Actions / backend

The variable 'x' is assigned but its value is never used
Title = "Update conflict";
Status = StatusCodes.Status409Conflict;
Type = "https://httpstatuses.com/409";
Detail = detail ?? "The resource was modified by another request. Please refresh and retry.";
}
}
//try commit again
//more comments
6 changes: 6 additions & 0 deletions Project.App/Project.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Project.Api.Services.Interface;
using Project.Api.Utilities.Middleware;
using Serilog;
using Project.Api.Infrastructure;

namespace Project.Api;

Expand Down Expand Up @@ -43,6 +44,11 @@ public static void Main(string[] args)
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//Infrastructure - add concurrency exception filter globally///added here
// Add exception filter to handle concurrency exceptions globally
builder.Services.AddControllers(o =>{
o.Filters.Add<ConcurrencyExceptionFilter>();});

var app = builder.Build();

app.UseMiddleware<GlobalExceptionHandler>();
Expand Down
Loading