2

我试图弄清楚如何从我的存储库将异常和错误返回到控制器级别,并能够在客户端调用我的 Web 服务时将自定义错误返回给客户端。

我的BookRepository课堂上有以下示例:

public BookViewModel GetBookById(Guid id)
{
      var Book = _Books.Collection.Find(Query.EQ("_id", id)).Single();
      return Book;
}

显然我的函数会比这复杂一点,但是如果我在一个不存在的 id 上调用这个方法,我会得到一个异常。如何让我的异常和自定义错误冒泡到我的控制器,然后在客户端响应中很好地显示

4

3 回答 3

3

就异常处理而言,即使是 Web 服务也应该遵循与任何其他代码相同的模式。这些最佳实践包括不使用自定义异常,除非调用者要根据异常类型进行编程选择。所以,

public BookViewModel GetBookById(Guid id)
{
    try
    {
      var Book = _Books.Collection.Find(Query.EQ("_id", id)).Single();
      return Book;
    }
    catch (SpecificExceptionType1 ex)
    {
        Log.Write(ex);
        throw new Exception("Some nicer message for the users to read", ex);
    }
    catch (SpecificExceptionType2 ex)
    {
        Log.Write(ex);
        throw new Exception("Some nicer message for the users to read", ex);
    }
    catch (Exception ex)
    {
        Log.Write(ex);
        throw;  // No new exception since we have no clue what went wrong
    }
}
于 2013-03-05T19:00:03.360 回答
1

what edmastermind29 mentioned is one common way to do it. i would usually the same way.

but sometimes developers like to catch the exception before the controller and return a result message based on enumerated value for example , so the controller would have no try catch blocks for that call, it will only need to check the status message.

you can use out parameter to check status and display messages for users accordingly.

this is how ASP.NET Membership provider is implemented. check the method create user in Membership provider for example:

http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.createuser(v=vs.100).aspx

于 2013-03-05T18:52:00.333 回答
0

放置try-catch可能在特定情况下失败的方法、LINQ 查询等(空值、空值、无效值等)。从那里,您可以捕获异常,并根据您要查找的内容抛出自定义异常。见下文。

public BookViewModel GetBookById(Guid id)
{
   try
   {
      var Book = _Books.Collection.Find(Query.EQ("_id", id)).Single();
      return Book;
   }
   catch (Exception e)
   {
      Log.Write(e)
      status = "Some Custom Message";
   }
   catch (DoesNotExistException dne)
   {
      Log.Write(dne)
      status = "Some Custom Message about DNE";
   }
}
于 2013-03-05T18:31:10.127 回答