gpt4 book ai didi

mysql - 无法捕获 MySqlException [Entity Framework WebAPI]

转载 作者:行者123 更新时间:2023-11-30 00:37:34 24 4
gpt4 key购买 nike

代码如下所示

public HttpResponseMessage PostUser(User user)
{
if (ModelState.IsValid)
{
try
{
db.Users.Add(user);
db.SaveChanges();
}
catch (MySqlException e)
{
....
}
}
}

由于重复的 Key,WebServer 返回 500 Intenal,但从未进入 catch block 。我想知道如何在上面的代码中捕获 MySqlException。

ExceptionMessage: "Duplicate entry 'TEST2' for key 'IX_User'"
ExceptionType: "MySql.Data.MySqlClient.MySqlException"

StackTrace:
MySql.Data.MySqlClient.MySqlStream.ReadPacket()
MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
MySql.Data.MySqlClient.MySqlDataReader.NextResult()
MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
MySql.Data.Entity.EFMySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()"

最佳答案

您可以通过SQLException来处理它,如下所示:

// your class code

try{
// do your work
}catch(SQLExcepetipn e){
// handle it
}

没有 MYSQL 异常类。

关于mysql - 无法捕获 MySqlException [Entity Framework WebAPI],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22031980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com