Improve error handling in InsertObjectProcedureHandler
Wrap SQL execution in try-catch and inject SqlExceptionOptions. Throw BadRequestException with a clear message when insert fails due to missing referenced entities, based on SqlException number. Other SQL exceptions are rethrown. This provides better feedback for foreign key/reference errors.
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
using DigitalData.Core.Abstraction.Application.Repository;
|
||||
using DigitalData.Core.Exceptions;
|
||||
using MediatR;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using ReC.Application.Common.Exceptions;
|
||||
@@ -7,6 +8,7 @@ using ReC.Application.EndpointParams.Commands;
|
||||
using ReC.Application.Endpoints.Commands;
|
||||
using ReC.Application.Results.Commands;
|
||||
using ReC.Application.Profile.Commands;
|
||||
using ReC.Application.Common.Options;
|
||||
|
||||
namespace ReC.Application.Common.Procedures.InsertProcedure;
|
||||
|
||||
@@ -41,7 +43,7 @@ public static class InsertObjectProcedureExtensions
|
||||
}
|
||||
}
|
||||
|
||||
public class InsertObjectProcedureHandler(IRepository repo) : IRequestHandler<InsertObjectProcedure, long>
|
||||
public class InsertObjectProcedureHandler(IRepository repo, SqlExceptionOptions sqlExceptionOptions) : IRequestHandler<InsertObjectProcedure, long>
|
||||
{
|
||||
public async Task<long> Handle(InsertObjectProcedure request, CancellationToken cancel)
|
||||
{
|
||||
@@ -110,6 +112,8 @@ public class InsertObjectProcedureHandler(IRepository repo) : IRequestHandler<In
|
||||
}
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
await repo.ExecuteQueryRawAsync(
|
||||
"EXEC [dbo].[PRREC_INSERT_OBJECT] " +
|
||||
"@pENTITY, @pADDED_WHO, @pADDED_WHEN, " +
|
||||
@@ -122,6 +126,17 @@ public class InsertObjectProcedureHandler(IRepository repo) : IRequestHandler<In
|
||||
"@oGUID OUTPUT",
|
||||
parameters,
|
||||
cancel);
|
||||
}
|
||||
catch (SqlException ex)
|
||||
{
|
||||
if (sqlExceptionOptions.SqlExceptionNumber.Contains(ex.Number))
|
||||
throw new BadRequestException(
|
||||
$"Insert '{request.Entity}' failed because one or more referenced entities do not exist. " +
|
||||
"Please verify the supplied identifiers and try again.\n" +
|
||||
ex.Message, ex);
|
||||
else
|
||||
throw;
|
||||
}
|
||||
|
||||
var guidParam = parameters.Last();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user