I am trying to figure out how to return exceptions and errors up to the controller level from my repository and be able to return custom errors to the client when they call my web service.
I have the following example from my BookRepository class:
public BookViewModel GetBookById(Guid id)
{
var Book = _Books.Collection.Find(Query.EQ("_id", id)).Single();
return Book;
}
obviously my function would be a little more complicated than this, but if i called this method on a id that did not exist i would get an exception. How can I have my exceptions and custom errors bubble up to my controller and then displayed nicely in the client response
Even a web service should follow the same patterns as any other code, with respect to exception handling. Those best practices include not using custom exceptions unless the caller is going to make a programmatic choice based on the exception type. So,
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With