I have a CustomException class, that is a wrapper on top of Exception class. This is the main class that i use when i handle Exceptions.
public class CustomException : Exception
{
public string ErrorMessage { get; private set; }
public HttpStatusCode HttpStatusCode { get; private set; }
public CustomException(string errorMessage)
: this(errorMessage, HttpStatusCode.InternalServerError)
{ }
public CustomException(string message, HttpStatusCode httpStatusCode)
{
ErrorMessage = message;
HttpStatusCode = httpStatusCode;
}
}
When i want to throw an exception, i use throw CustomException() method.
However, i want to create some wrappers on top of this CustomException() as well, for example:
public class ApplicationNotFoundException : Exception
{
public ApplicationNotFoundException(Application application)
{
string message = string.Format(@"Application ""{0}"" was not found", application.ApplicationName);
throw new CustomException(message, HttpStatusCode.NotFound);
}
}
And i throw exception line this: throw new ApplicationNotFoundException(application)
Basically i am throwing an Exception from another Exception.
Is this approach bad?
This is basically not the approach to use exceptions.
Creating custom exceptions serves your custom needs, that if built-in exceptions can't handle this.
There are some ways for you:
CustomException is your "base" class and ApplicationNotFoundException is a derived one, this is the preferred way of specializing.or
structs if you just want to send some information and don't need to work on the particular objects themselves)EDIT
Also, which is very important, consider stack unwinding as a factor of efficiency. Throwing an exception forces the call stack to be unwound, which takes a little time, too!
You can do it your way, of course, but it might tighten things a little up, which could be unnecessary.
For some background, consider MSDN.
Let the user of your ApplicationNotFoundException decide when it is appropriate to throw.
Don't do it in the constructor of your ApplicationNotFoundException.
Instead derive your ApplicationNotFoundException from CustomException
public class ApplicationNotFoundException : CustomException
{
public ApplicationNotFoundException(Application application)
{
string message = string.Format(@"Application '{0}' was not found", application.ApplicationName);
base.ErrorMessage = message
base.HttpStatusCode = HttpStatusCode.NotFound;
}
}
public class CustomException : Exception
{
public string ErrorMessage { get; internal set; }
public HttpStatusCode HttpStatusCode { get; internal set; }
public CustomException(string errorMessage)
: this(errorMessage, HttpStatusCode.InternalServerError)
{ }
public CustomException(string message, HttpStatusCode httpStatusCode)
{
ErrorMessage = message;
HttpStatusCode = httpStatusCode;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With