Improve error handling in DeleteObjectProcedureHandler

Refactored DeleteObjectProcedureHandler to inject SqlExceptionOptions and wrap stored procedure execution in a try-catch block. Added logic to throw custom exceptions (DeleteObjectFailedException, BadRequestException) based on result codes and SQL exception numbers, enhancing robustness and configurability of error handling.
This commit is contained in:
Developer 02
2026-01-22 01:53:40 +01:00
parent 51b9c62188
commit 54f412ced2

View File

@@ -1,7 +1,9 @@
using DigitalData.Core.Abstraction.Application.Repository; using DigitalData.Core.Abstraction.Application.Repository;
using DigitalData.Core.Exceptions;
using MediatR; using MediatR;
using Microsoft.Data.SqlClient; using Microsoft.Data.SqlClient;
using ReC.Application.Common.Exceptions; using ReC.Application.Common.Exceptions;
using ReC.Application.Common.Options;
namespace ReC.Application.Common.Procedures.DeleteProcedure; namespace ReC.Application.Common.Procedures.DeleteProcedure;
@@ -47,7 +49,7 @@ public static class DeleteObjectProcedureExtensions
} }
} }
public class DeleteObjectProcedureHandler(IRepository repo) : IRequestHandler<DeleteObjectProcedure, int> public class DeleteObjectProcedureHandler(IRepository repo, SqlExceptionOptions sqlExceptionOptions) : IRequestHandler<DeleteObjectProcedure, int>
{ {
public async Task<int> Handle(DeleteObjectProcedure request, CancellationToken cancel) public async Task<int> Handle(DeleteObjectProcedure request, CancellationToken cancel)
{ {
@@ -59,20 +61,30 @@ public class DeleteObjectProcedureHandler(IRepository repo) : IRequestHandler<De
new SqlParameter("@pFORCE", (object?)request.Force ?? DBNull.Value) new SqlParameter("@pFORCE", (object?)request.Force ?? DBNull.Value)
}; };
var result = await repo.ExecuteQueryRawAsync( try
"DECLARE @RC SMALLINT = 0; " +
"EXEC @RC = [dbo].[PRREC_DELETE_OBJECT] " +
"@pENTITY, @pSTART, @pEND, @pFORCE; " +
"SELECT @RC;",
parameters,
cancel);
// The stored procedure returns 0 on success, error codes > 0 on failure
if (result > 0)
{ {
throw new DeleteObjectFailedException(request, $"DeleteObject stored procedure failed with error code: {result}"); var result = await repo.ExecuteQueryRawAsync(
} "DECLARE @RC SMALLINT = 0; " +
"EXEC @RC = [dbo].[PRREC_DELETE_OBJECT] " +
"@pENTITY, @pSTART, @pEND, @pFORCE; " +
"SELECT @RC;",
parameters,
cancel);
return result; // The stored procedure returns 0 on success, error codes > 0 on failure
if (result > 0)
{
throw new DeleteObjectFailedException(request, $"DeleteObject stored procedure failed with error code: {result}");
}
return result;
}
catch (SqlException ex)
{
if (sqlExceptionOptions.SqlExceptionNumber.Contains(ex.Number))
throw new BadRequestException(ex.Message, ex);
else
throw;
}
} }
} }