如何获取或设置用户友好的数据库错误.net core

时间:2018-01-18 07:16:25

标签: c# sql-server entity-framework .net-core

我正在使用angular和typescript开发.net核心Web应用程序,我需要的是以用户友好的方式跟踪错误。

 public JsonResult Post([FromBody] Data product)
{
  Response.StatusCode = 200;


  try
  {
    repo.Insert(new TblStudentRegisteration() { RgNo = product.rgno , Name = product.name , FatherName = product.FatherName});
  }
  catch (Exception e)
  {
    Response.StatusCode = 400;
    return Json(e.ToString());
  }
  return Json("ok");
}

其中RGNo是主键,我需要的是数据库引发任何错误,错误以用户友好的方式返回?

就像用户给RgNo两次异常抛出一样

  

“Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时发生错误。有关详细信息,请参阅内部异常.---> System.Data.SqlClient.SqlException:违反PRIMARY KEY约束'PK_tbl_StudentRegisteration'。无法插入重复项键入对象'dbo.tbl_StudentRegisteration'。   该语句已终止。      在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,Boolean breakConnection,Action 1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction)      在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,Boolean callerHasConnectionLock,Boolean asyncClose)      在System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,Boolean& dataReady)      在System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()      在System.Data.SqlClient.SqlDataReader.get_MetaData()      在System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,RunBehavior runBehavior,String resetOptionsString)      在System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,Boolean async,Int32 timeout,Task& task,Boolean asyncWrite,SqlDataReader ds)      在System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,TaskCompletionSource 1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader() at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary 2 parameterValues)      在Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection,IReadOnlyDictionary 2 parameterValues) at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple 2个参数)      在Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute [TState,TResult](TState状态,Func 3 operation, Func 3 verifySucceeded)      在Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute [TState,TResult](IExecutionStrategy strategy,TState state,Func 2 operation) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable 1 commandBatches,IRelationalConnection connection)      在Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList 1 entries) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList 1 entriesToSave)      在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)      在Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)      在Microsoft.EntityFrameworkCore.DbContext.SaveChanges()      在RepositoryData.Repository`1.Insert(T entity)in

我明白这是重复输入的问题,来自这个给定的句子。

  

违反PRIMARY KEY约束'PK_tbl_StudentRegisteration'。无法在对象'dbo.tbl_StudentRegisteration'

中插入重复键

用户如何理解这一点?直到并且除非我们以最佳方式定义它们。

有最简单的方法吗?

修改 有一件事我想清楚,我知道有很多方法可以做到这一点,首先检查这个RgNo是否存在,然后将其发布到DB,但也有一些其他的重复,使用ex.Message会给出简短形式等等,但我希望每件事都能让事情变得更轻松。

0 个答案:

没有答案