From 54f412ced2ffa6db86e46a8cc4d2357c36f87511 Mon Sep 17 00:00:00 2001 From: Developer 02 Date: Thu, 22 Jan 2026 01:53:40 +0100 Subject: [PATCH] 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. --- .../DeleteProcedure/DeleteObjectProcedure.cs | 38 ++++++++++++------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/src/ReC.Application/Common/Procedures/DeleteProcedure/DeleteObjectProcedure.cs b/src/ReC.Application/Common/Procedures/DeleteProcedure/DeleteObjectProcedure.cs index dad028b..861022e 100644 --- a/src/ReC.Application/Common/Procedures/DeleteProcedure/DeleteObjectProcedure.cs +++ b/src/ReC.Application/Common/Procedures/DeleteProcedure/DeleteObjectProcedure.cs @@ -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 +public class DeleteObjectProcedureHandler(IRepository repo, SqlExceptionOptions sqlExceptionOptions) : IRequestHandler { public async Task Handle(DeleteObjectProcedure request, CancellationToken cancel) { @@ -59,20 +61,30 @@ public class DeleteObjectProcedureHandler(IRepository repo) : IRequestHandler 0 on failure + if (result > 0) + { + throw new DeleteObjectFailedException(request, $"DeleteObject stored procedure failed with error code: {result}"); + } - // The stored procedure returns 0 on success, error codes > 0 on failure - if (result > 0) + return result; + } + catch (SqlException ex) { - throw new DeleteObjectFailedException(request, $"DeleteObject stored procedure failed with error code: {result}"); + if (sqlExceptionOptions.SqlExceptionNumber.Contains(ex.Number)) + throw new BadRequestException(ex.Message, ex); + else + throw; } - - return result; } }