I have created a custom exception however when it is fired, I’m not getting the message I expect.
Instead of the Unhandled Execution Error message I am expecting the override in my custom class to fire which would be The section 'UIButtons' does not contain an element with element key 'Save' based on the exception being thrown below.
Can anyone help me diagnose why this is happening?
using System;
namespace Payntbrush.Infrastructure.Application.Exceptions.Configuration
{
[Serializable]
public class ConfigElementDoesNotExistException : Exception
{
private string _sectionName;
private string _elementName;
public ConfigElementDoesNotExistException(string sectionName, string elementName, string errorMessage = "")
: base(errorMessage)
{
_sectionName = sectionName;
_elementName = elementName;
}
public ConfigElementDoesNotExistException(string sectionName, string elementName, string errorMessage, Exception innerEx)
: base(errorMessage, innerEx)
{
_sectionName = sectionName;
_elementName = elementName;
}
/// <summary>
/// Gets a message that describes the current exception
/// </summary>
public override string Message
{
get
{
string exceptionMessage;
if (String.IsNullOrEmpty(base.Message))
{
exceptionMessage = base.Message;
}
else
{
exceptionMessage = String.Format("The section '{0}' does not contain an element with element key '{1}'", _sectionName, _elementName);
}
return exceptionMessage;
}
}
}
}
To throw it I am using:
throw new ConfigElementDoesNotExistException("UIButtons", "Save");
And when it fires I get this message
Unhandled Execution Error
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Payntbrush.Infrastructure.Application.Exceptions.Configuration.ConfigElementDoesNotExistException:
I think you should change the
ifstatement in yourgetoverride ofMessageto:Note the
!.At present, if the message supplied on construction is null or empty, then you’re returning null/empty – so the framework is filling in it’s own when reporting the exception.
Presumably you meant to supply your own message if it’s null/empty.
Minor update – advisory
Incidentally – I generally do this kind of thing in the constructor:
In your case I would do it like this with just one constructor:
Also don’t forget the protected constructor and
GetObjectDataoverride to ensure your exception can be saved/loaded and marshalled properly.