Custom error handling ASP.NET
I want to use custom exception handling, for example
instead of using (Exception ex) i want to use 开发者_JAVA技巧(LoginException ex) or (RegistrationException ex) or (SomeNameException ex)
is it possible to design such custom exception handling in ASP.NET webforms?
Yes but what you need to do is first create your own custom exceptions. You need to derive your exception from the Exception base class. Heres an example:
[Serializable]
public class LoginFailedException: Exception
{
public LoginFailedException() : base()
{
}
public LoginFailedException(string message)
: base(message)
{
}
public LoginFailedException(string message, Exception innerException)
: base(message, innerException)
{
}
protected LoginFailedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
Then in your code, you would need to raise this exception appropriately:
private void Login(string username, string password)
{
if (username != DBUsername && password != DBPassword)
{
throw new LoginFailedException("Login details are incorrect");
}
// else login...
}
private void ButtonClick(object sender, EventArgs e)
{
try
{
Login(txtUsername.Text, txtPassword.Text);
}
catch (LoginFailedException ex)
{
// handle exception.
}
}
You mean something like:
try{ somefunc(); }catch(LoginException ex){ }catch(RegistrationException ex){ }catch(SomeNameException ex){ }
Or do you mean coding the classes to throw the exceptions?
精彩评论