3

I am using Entity Framework and when a DbUpdateException is thrown from dbContext.SaveChanges() how do I create a custom exception and throw that instead?

Would I create a condition on each SQL constraint that can be thrown:

if (e.InnerException.InnerException.Message.Contains("UNIQUE KEY"))
{
     throw new CustomException("message");
}

1 Answer 1

2

EDIT: That approach makes good sense to me. If you know your application/DB is going to have a specific error, and it will help you or your users to have a specific custom exception type that quickly identifies what would otherwise be a somewhat complex or specific scenario, then absolutely yes. It's good practice to use both the exception type and the exception message to make the error as clear as possible. My code below is an even simpler example than what you seem to drilling down into. Rather than letting other code end up with a null reference exception or some other consequence, I beat everything to the punch with throw new DatabaseDataNotFoundException("Cannot find ServerAppConfiguration value for {0}", key);.

Just make your own exception class that inherits from Exception, here's a custom exception I use for exactly that purpose:

public class DatabaseDataNotFoundException : Exception
{
    public DatabaseDataNotFoundException() : base() { }

    public DatabaseDataNotFoundException(string message) : base(message) { }

    public DatabaseDataNotFoundException(string message, params object[] args)
        : base(String.Format(CultureInfo.CurrentCulture, message, args)) { }

    public DatabaseDataNotFoundException(string message, Exception inner)
        : base(message, inner) { }

    public DatabaseDataNotFoundException(string message, Exception inner, params object[] args)
        : base(String.Format(CultureInfo.CurrentCulture, message, args), inner) { }

    protected DatabaseDataNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

Then your code becomes:

if (e.InnerException.InnerException.Message.Contains("UNIQUE KEY"))
{
    throw new DatabaseDataNotFoundException("message");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.