处理自定义异常类

时间:2014-09-27 08:12:26

标签: c# asp.net-mvc exception-handling

我正在开发一个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
               {
               }
    }

1 个答案:

答案 0 :(得分:0)

您必须从服务中抛出这些例外,以便它们被捕获。

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.";
                }