I'm here again with another question about MVC.
Here is the d开发者_如何学运维eal. I have a simple table/class with an Id and a Name. Names suppossed to be unique, and are modeled like that in the DB.
I created my controller and everything just works fine. But if I try to insert a name that already exists, an exception should be thrown. I'm just not finding what is the correct kind of exception and it's namespace. The error must be coming from the DB, so...
Any ideas?
Thanks
Just declare your own exception class.
public class DuplicateNameException : Exception {}
You'll probably want to add some constructors to ensure that the message gets set appropriately, but it doesn't need to be much more difficult than that.
Updated after clarification from OP: So the DB throwing an exception and you just want to make it more obvious what the problem was. What I suggest in this case is that you keep the DB exception as the InnerException
, and rethrow something better. So declare DuplicateNameException
as something like this:
public class DuplicateNameException : Exception
{
public DuplicateNameException(DBException ex)
: base("Duplicate name!", ex)
{}
}
Then where you need to do DB operations:
try
{
DoDatabaseOperation();
}
catch (DBException ex)
{
if (IsDuplicateNameException(ex))
{
throw new DuplicateNameException(ex);
}
else
{
throw; // use the no-argument form of "throw" to ensure you don't break the stack trace!
}
}
精彩评论