Reputation: 521
My goal is to verify if an object's name already exists in my EF Core db, if so: throw a specific error. However, I receive a 500 internal server error.
First I created an index on name in DbContext, including IsUnique and some code to catch the exception in the repository.
Can I maybe add something in the controller that says if errorcode == 2601 then throw "the required exception"? Or is there another way to overcome this 500 error? Thanks in advance for the help!
DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>()
.HasIndex(c => c.Name)
.IsUnique();
}
Repository:
public async Task<bool> SaveAsync()
{
try
{
return (await _context.SaveChangesAsync() >= 0);
}
catch (DbUpdateException dbEx)
{
SqlException sqlException = dbEx.InnerException as SqlException;
if (sqlException.Number == 2601)
{
throw new Exception("Name already exists. Please provide a different name.");
}
throw new Exception(dbEx.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
Controller:
Public async Task<IActionResult> AddCar([FromBody] Car car)
...
if (!await _repository.SaveAsync())
{
throw new Exception("Fail on save...");
}
...
Upvotes: 1
Views: 2114
Reputation: 2619
If you are using ASP.Net Core, you can create you own exception handling middleware.
The error handling middleware class itself may look something like:
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate m_next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
m_next = next;
}
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await m_next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
HttpStatusCode httpStatusCode = HttpStatusCode.InternalServerError;
string message = "Something is wrong!";
if (exception is MyException)
{
httpStatusCode = HttpStatusCode.NotFound; // Or whatever status code you want to return
message = exception.Message; // Or whatever message you want to return
}
string result = JsonConvert.SerializeObject(new
{
error = message
});
context.Response.StatusCode = (int)httpStatusCode;
context.Response.ContentType = "application/json";
return context.Response.WriteAsync(result);
}
}
You register in Startup.Configure() as:
app.UseMiddleware(typeof(ErrorHandlingMiddleware));
Upvotes: 1
Reputation: 36
Change stdoutLogEnabled="false" to true and then check the logs at stdoutLogFile=".\logs\stdout". The error(s) there might tell you something.
Check that you set up right Environment Name using ASPNETCORE_ENVIRONMENT environment variable as so use correct settings like connection string. On your machine by default you have "Development" environment.
You may use Error Handling middlewares for showing exceptions like
app.UseDeveloperExceptionPage();
Upvotes: 0