views:

37

answers:

1

Hello guys, I'm here again with another question about MVC.

Here is the deal. 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

+2  A: 

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!
    }
}
JSBangs
Sure I could do that, but is there a way with MVC to identify a priori which error was generated by the database?Thanks
George
@George, I'm not clear on your question. Is this an exception that is *already* thrown by the database layer for which you want a better message, or a new exception that you hope to throw?
JSBangs
Hello JS. My exception is already thrown by the database layer. The way I managed this to work is to look for specific database error numbers and add a specific message. Not the prettiest way, but it works. Any ideas?
George
@George, I understand now. See my updated answer.
JSBangs