代码看起来像这样
public HttpResponseMessage PostUser(User user)
{
if (ModelState.IsValid)
{
try
{
db.Users.Add(user);
db.SaveChanges();
}
catch (MySqlException e)
{
....
}
}
}
WebServer由于重复Key而返回500 Internal,但从未进入catch块。 我想知道如何在上面的代码中捕获MySql异常。
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()"
答案 0 :(得分:0)
你可以通过 SQLException 来处理它:
// your class code
try{
// do your work
}catch(SQLExcepetipn e){
// handle it
}
没有MYSQL异常类。