I created a custom exception
public class InvalidUsernameException : ApplicationException
{
public InvalidUsernameException()
{
}
}
After that I throw this exception in a method
public static DataTable GetTableForApproval()
{
using (var connection = Utils.Database.GetConnection())
using (var command = new SqlCommand("SELECT [UserID], [Username], [Email], [Role], [Date] FROM [Users] WHERE [Role] = @role", connection))
{
command.Parameters.AddWithValue("@role", "Waiting");
using (var reader = command.ExecuteReader())
{
if (reader == null || !reader.HasRows)
throw new NoFormsForAuthenticaionException();
var table = new DataTable();
table.Columns.Add("UserID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Email", typeof(string));
table.Columns.Add("Role", typeof(string));
table.Columns.Add("Registration date", typeof(DateTime));
while (reader.Read())
table.Rows.Add((int)reader["UserID"], (string)reader["Username"], (string)reader["Email"], (string)reader["Role"], (DateTime)reader["Date"]);
return table;
}
}
}
And when I use these method I catch the exception
try
{
GvApproveUser.DataSource = Authentication.GetTableForApproval();
GvApproveUser.DataBind();
}
catch (NoFormsForAuthenticaionException)
{
Error.HandleError("There is no forms for approval");
}
This is the code behind the Error page
public partial class Error
{
public static string GetUrl(string message)
{
return string.Format("~/Error.aspx?errorMessage={0}", message);
}
public static void HandleError(string message)
{
HttpContext.Current.Response.Redirect(GetUrl(message), false);
}
protected override void OnPreRender(System.EventArgs e)
{
base.OnPreRender(e);
LblError.Text = ErrorMsg;
}
private string ErrorMsg
{
get
{
return Request["errorMessage"] ?? string.Empty;
}
}
}
Is there a easier way to post this error message? Can I do this without violating the rules of 3-tier architecture? Is there another way?
public class InvalidUsernameException : ApplicationException
{
public InvalidUsernameException()
{
Error.HandleError("There is no forms for approval");
}
}
The first thing to note is that you are using an exception for something that does not appear to be an exceptional circumstance; having no rows seems like both a reasonable and expected state of affairs. So, if it isn’t an exceptional case, don’t use an exception.
I’d probably change the data access method to not throw, and then simply check whether there are any rows in the table, which means your code would simplify down to something like this:
The next potential simplification is to decide whether you really want to redirect to an error page for something like this. Why not just show a message instead of the gridview that indicates there is nothing to approve? Then you keep it all on one page and everything becomes very simple as there is just one page with no custom exceptions and no special error page, e.g.