显示在EF Core存储库中创建的异常,而不是500错误

时间:2018-11-08 15:34:20

标签: c# exception asp.net-core repository ef-core-2.0

我的目标是验证EF Core数据库中是否已经存在对象的名称,如果存在:抛出特定错误。但是,我收到500个内部服务器错误。

首先,我在DbContext中为名称创建了一个索引,包括 IsUnique 和一些代码以在存储库中捕获异常。

我是否可以在控制器中添加一些内容,说明错误代码== 2601,然后抛出“所需的异常”?还是有另一种方法来克服此500错误?预先感谢您的帮助!

DbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Car>()
        .HasIndex(c => c.Name)
        .IsUnique();
}

存储库

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);
    }
}

控制器

Public async Task<IActionResult> AddCar([FromBody] Car car)
    ...
    if (!await _repository.SaveAsync())
    {
        throw new Exception("Fail on save...");
    }
    ...

2 个答案:

答案 0 :(得分:1)

如果您使用的是ASP.Net Core,则可以创建自己的exception handling middleware

错误处理中间件类本身可能类似于:

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);
    }
}

您在Startup.Configure()中注册为:

app.UseMiddleware(typeof(ErrorHandlingMiddleware));

答案 1 :(得分:0)

  1. 将stdoutLogEnabled =“ false”更改为true,然后检查stdoutLogFile =“。\ logs \ stdout”中的日志。那里的错误可能会告诉您一些情况。

  2. 检查是否使用ASPNETCORE_ENVIRONMENT环境变量设置了正确的环境名称,因此请使用正确的设置(例如连接字符串)。默认情况下,您的计算机上具有“开发”环境。

  3. 您可以使用错误Handling middlewares来显示类似的异常

    app.UseDeveloperExceptionPage();