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:
@@ -1,7 +1,9 @@
|
||||
using DigitalData.Core.Abstraction.Application.Repository;
|
||||
using DigitalData.Core.Exceptions;
|
||||
using MediatR;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using ReC.Application.Common.Exceptions;
|
||||
using ReC.Application.Common.Options;
|
||||
|
||||
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)
|
||||
{
|
||||
@@ -59,20 +61,30 @@ public class DeleteObjectProcedureHandler(IRepository repo) : IRequestHandler<De
|
||||
new SqlParameter("@pFORCE", (object?)request.Force ?? DBNull.Value)
|
||||
};
|
||||
|
||||
var result = await repo.ExecuteQueryRawAsync(
|
||||
"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)
|
||||
try
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user