C#C
C#2y ago
Mek

✅ Catching different errors using System.Data.SQLite

public void CreateSomeTable()
{
  Using SQLiteConnection conn = new(_dbFile);
  Using SQLiteCommand cmd = conn.CreateCommand();

  conn.Open();

  cmd.CommandText = @"CREATE TABLE IF NOT EXISTS
                      [login] (
                      [Username] VARCHAR(15),
                      [Password] VARCHAR(30),
                      UNIQUE(Username)
                      )";
  try
  {
      cmd.ExecuteNonQuery();
  }
  catch (SQLiteException ex)
  {
      throw new SQLiteExecption ex;
  }
}

public void InsertNewUser(UserModel user)
{
  Using SQLiteConnection conn = new(_dbFile);
  ...

  cmd.CommandText = @"INSERT INTO login(Username, Password) VALUES ($un, $pw)";
  cmd.Parameters.AddWithValue("$un", user.Username);
  cmd.Parameters.AddWithValue("$pw", user.Password);

  try
  {
      cmd.ExecuteNonQuery();
  }
  catch (SQLiteException ex)
  {
      throw new SQLiteException(ex.Message);
  }
}
so I'm wanting to write a custom class that error handles my database. For example:
public class DatabaseErrorHandler()
{
  public void HandleUniqueEntryError()
  {
      // some code here
  }
}
I would somehow (idk how) use the class within the code above for adding a new user to the database. In the create database function, the Username field is unique. A user tries to create a new account with a username that already exists. I would like for the process to be something like

  1. user clicks create user button call database function
  2. database tries to save -> send error to custom error handler class
  3. function for unique errors sends back some type of value to the View for the user to tell them that the username already exists and to try again
How would I go about doing this? I wanted to do a custom class so that I could call the error class anywhere I needed throughout my database file and be able to still have the program act accordingly.
Was this page helpful?