处理自定义异常类



我正在开发一个MVC应用程序。

我正在尝试定义我自己的异常类。我第一次做这个结构。。。

我还需要在异常类中添加什么,比如构造函数之类的,这样它才能很好地工作?

 public ActionResult Edit(EmployeeVM employeeVM)
    {
                EmployeeService employeeService = new PartyService();
                try
                {
                    PartyService partyService = new PartyService();
                     partyService.Update(PartyVM);
                }
                catch (DuplicateEntityExcpetion e)
                {
                    TempData["error"] = e + "Party you are trying to add is already exist.";
                }
                catch (InvalidDataException e)
                {
                    TempData["error"] =  e + "Data which you are trying to add is not valid.";
                }

               public class InvalidDataException : Exception
               {
               }
               public class DuplicateEntityExcpetion : Exception
               {
               }
    }

您必须从服务中抛出这些异常,以便在此处捕获它们。

throw new DuplicateEntityExcpetion("Your Query or Message");
throw new InvalidDataException ("Your Query or Message");

此外,处理一个通用异常是一种很好的做法,这样您就可以处理所有异常。

 catch (Exception e)
                {
                    TempData["error"] =  e + "Data which you are trying to add is not valid.";
                }

最新更新