代码看起来像这样
public HttpResponseMessage PostUser(User user)
{
if (ModelState.IsValid)
{
try
{
db.Users.Add(user);
db.SaveChanges();
}
catch (MySqlException e)
{
....
}
}
}
WebServer由于密钥重复而返回500 Internal,但从未输入catch块。
我想知道如何在上述代码中捕获MySql Exception。
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/