例外没有给出预期的消息

时间:2012-04-03 11:01:38

标签: c# asp.net exception

我创建了一个自定义异常但是当它被触发时,我没有收到我期望的消息。

而不是Unhandled Execution Error消息,我希望我的自定义类中的覆盖根据下面抛出的异常触发The section 'UIButtons' does not contain an element with element key 'Save'

任何人都可以帮我诊断为什么会这样吗?

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;
            }
        }
    }
}

扔掉它我正在使用:

throw new ConfigElementDoesNotExistException("UIButtons", "Save");

当它发射时,我收到此消息

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: 

1 个答案:

答案 0 :(得分:1)

我认为您应该将if覆盖get的{​​{1}}语句更改为:

Message

请注意if (!String.IsNullOrEmpty(base.Message))

目前,如果构造中提供的消息为null或为空,那么您将返回null / empty - 因此框架在报告异常时会自行填充。

如果它是空/空,大概你打算提供自己的消息

次要更新 - 咨询

顺便说一句 - 我通常在构造函数中执行此类操作:

!

在你的情况下,我只需要一个构造函数就可以这样做:

public MyException(string message) : base(message ?? "Default message") { }

另外,请不要忘记受保护的构造函数和public ConfigElementDoesNotExistException(string sectionName, string elementName, string errorMessage = null, Exception innerEx = null) : base(errorMessage ?? string.Format("The section {0} doesn't ... {1}", sectionName ?? "[unknown]", elementName ?? "[unknown]") , innerEx) { _sectionName = sectionName; _elementName = elementName; } 覆盖,以确保可以正确保存/加载和编组异常。