In general I would strictly separate data access and return codes of the web API. So I'd first go with some kind of repository to query data:
public abstract class RepositoryBase
{
protected void Validate(dynamic dynamicObjectData) { ... }
}
I would not use stored procedures, but operate on context with EF entities (all queries are typed), but I guess you have a good reason to use SPs, so you could go with:
public class CompanyRepository : RepositoryBase
{
public void UpsertCompany(Company company)
{
var result = _context.Set<sp_Upsert_Company>().FromSqlInterpolated($"sp_Upsert_Company {master_Company.Name},{uID}").ToList().FirstOrDefault();
Validate(result);
}
}
Validate function shall throw exceptions if something is wrong:
if (dynamicObjectData.Code == -400)
{
throw new MyNotFoundException();
}
So data layer queries data and throws if something bad happens.
Now you register a central exception handler on your ApplicationBuilder:
app.UseExceptionHandler(
builder => builder.Run(async context =>
{
var exceptionFeature = context.Features.Get<IExceptionHandlerFeature>();
if (exceptionFeature != null)
{
var exception = exceptionFeature.Error;
// Handle all your app exceptions in one place and decide which code to return, create a custom error:
...
context.Response.StatusCode = error.StatusCode; // Choose based on exception
await context.Response.WriteAsync(JsonConvert.SerializeObject(error));
})
So you encapsulate bad return codes with exceptions, catch them in one place, and decide what HTTP code to return.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…