Programing

.NET : 필요한 구성 설정이 누락되면 어떤 예외가 발생합니까?

crosscheck 2020. 7. 22. 08:07
반응형

.NET : 필요한 구성 설정이 누락되면 어떤 예외가 발생합니까?


표준 시나리오는 다음과 같습니다.

if(string.IsNullOrEmpty(Configuration.AppSettings["foobar"]))
   throw new SomeStandardException("Application not configured correctly, bozo.");

문제는 어떤 예외 SomeStandardException가 있어야하는지 완전히 확신하지 못한다 는 것입니다.

나는 3.5 프레임 워크를 숙독하고 두 후보들을 발견 ConfigurationException하고 ConfigurationErrorsException.

System.Configuration.ConfigurationException

구성 시스템 오류가 발생했을 때 발생하는 예외입니다.

비고

ConfigurationException응용 프로그램을 시도 읽거나 구성 파일에 기록 데이터를하지만 실패 할 경우 예외가 발생합니다. 구성 파일의 형식이 잘못된 XML, 파일 권한 문제 및 유효하지 않은 값을 가진 구성 속성이 여기에 해당 할 수 있습니다.

노트 :

ConfigurationException개체의 호환성을 유지한다. ConfigurationErrorsException구성 시스템 오브젝트가 오브젝트를 대체합니다.

이 예외는 실제로 내가 필요한 것에 완벽하게 들리지만, atthay에서 ixnay로 표시되지 않습니다.

이것은 우리를 완전히 수수께끼로 만듭니다 ConfigurationErrorsException.

System.Configuration.ConfigurationErrorsException

현재 값이 EnableSessionState 값 중 하나가 아닙니다.

보시다시피, 설명서는 완전히 쓸모가 없습니다. (이것은 지역 및 온라인 도움말 모두에서 그런 식입니다.) 수업 자체를 살펴보면 내가 원하는 것에 지나치게 과도하다는 것을 알 수 있습니다.

간단히 말해서, 응용 프로그램 구성 설정이 없거나 유효하지 않은 값을 포함 할 때 발생하는 표준 예외가 필요합니다. 응용 프로그램에서 프레임 워크에 예외가 있다고 생각합니다. (이것은 분명히 보이지만 더 이상 사용되지 않는 것으로 표시 되었으며 범위가 훨씬것으로 대체되었습니다 .)

이 솔루션에 어떤 솔루션을 사용하고 있습니까?이 문제를 해결하고 내 예외를 굴려야합니까?

부록 편집

일부는 기본값을 제공 할 수 있는지 묻고 계속 진행합니다. 어떤 경우에는 그렇습니다. 그런 경우에는 예외가 발생하지 않습니다. 그러나 특정 설정의 경우에는 적용되지 않습니다. 예 : 데이터베이스 서버 이름 및 자격 증명, 인증 서버 및 설치된 타사 응용 프로그램의 경로

또한 내가 주로 작업하는 응용 프로그램은 배치 모드로 실행되는 콘솔 응용 프로그램이며 기본 방법으로 잡히고 제대로 구성되지 않은 경우 적절하게 기록 된 예외를 throw하고 싶습니다. (내가 상속 한 레거시 코드이며 현재 모든 것이 복숭아 라고 가정합니다 .)


프레임 워크의 기존 예외로 예외를 던지는 데 제한이 없습니다. 기존 예외를 사용하기로 결정한 경우 반드시 해당 문서를 반드시 따라야 할 필요는 없습니다. 어떻게 '문서는 설명합니다 프레임 워크는 특정 예외를 사용하지만 방법에 대한 제한을 의미하지 않는다 당신이 기존의 예외 재사용 / 사용을 선택합니다.

문서화하고 구성 값이 누락 된 특정 경우에 발생하는 예외를 명확하게 나타내는 한 응용 프로그램입니다. 원하는 예외를 사용할 수 있습니다. 측값을 매우 구체적으로 표시 하려면 고유 한 ConfigurationSettingMissing 예외를 작성하는 것이 좋습니다.

[Serializable]
public class ConfigurationMissingException : ConfigurationErrorsException
{}

편집 :이 경우 자신의 예외를 작성하면 프레임 워크 또는 응용 프로그램에서 예외가 발생하는 위치와 관련하여 혼동되지 않도록 보장하는 추가 이점이 있습니다. 프레임 워크는 사용자 지정 예외를 발생시키지 않습니다.

업데이트 : 의견에 동의하므로 하위 클래스를 Exception에서 ConfigurationErrorsException으로 변경했습니다. 응용 프로그램 별 예외가 필요하지 않은 경우 예외 클래스를 피하면서 가능한 경우 기존 Framework 예외의 사용자 지정 예외를 하위 클래스로 만드는 것이 일반적으로 좋은 생각이라고 생각합니다.


개인적으로 InvalidOperationException을 사용 합니다 . 구성 시스템이 아닌 객체 상태에 문제가 있기 때문입니다. 결국, 이러한 설정을 코드로 설정하고 구성하지 않아야합니까? 여기서 중요한 부분은 app.config에 줄이 없지만 필요한 정보가 없다는 것입니다.

나에게, ConfigurationException (그리고 잘못 대체 된 MSDN 문서에도 불구하고 ConfigurationErrorsException 대신 사용)은 Configuration의 저장, 읽기 등의 오류에 대한 것입니다.


Daniel Richardson이 말했듯이 ConfigurationErrorsException 이 사용됩니다. 일반적으로 사용자 정의 예외 유형을 처리 할 시나리오가있는 경우에만 사용자 정의 예외 유형을 작성하는 것이 좋습니다. 일반적으로 치명적인 구성 오류의 경우는 드물기 때문에 기존 ConfigurationErrorsException 유형을 다시 사용하는 것이 더 적합합니다.

.NET 2.0 이전에는 System.Configuration.ConfigurationException 을 사용하는 것이 좋습니다 . .NET 2.0에서는 ConfigurationException이 더 이상 사용되지 않게되었으며 권장 사항이 ConfigurationErrorsException을 사용하도록 변경되었습니다.

도우미 메서드를 사용하여 예외를 throw하여 .NET 1.x에서 2.0으로 마이그레이션하거나 Microsoft가 권장 사항을 다시 변경하기로 결정한 경우 한 곳에서 발생하는 예외를 쉽게 변경할 수 있습니다.

if(string.IsNullOrEmpty(Configuration.AppSettings("foobar")))
{
   throw CreateMissingSettingException("foobar");
}

...

private static Exception CreateMissingSettingException(string name)
{
    return new ConfigurationErrorsException(
        String.Format
        (
        CultureInfo.CurrentCulture,
        Properties.Resources.MissingConfigSetting,
        name
        )
        );
}

무엇에 대해 System.Configuration.SettingsPropertyNotFoundException?


ConfigurationErrorsException설명하는 상황에서 발생하는 올바른 예외입니다. MSDN 설명서의 이전 버전 ConfigurationErrorsException이 더 적합합니다.

http://msdn.microsoft.com/en-us/library/system.configuration.configurationerrorsexception(VS.80).aspx

이전 MSDN 요약 및 설명은 다음과 같습니다.

  • The exception that is thrown when a configuration-system error has occurred.
  • The ConfigurationErrorsException exception is thrown when any error occurs while configuration information is being read or written.

The ConfigurationElement class (which is the base class of many config-related classes, like ConfigurationSection) has a method called OnRequiredPropertyNotFound (there are other helper methods too). You can maybe call those.

The OnRequiredPropertyNotFound is implemented like this:

protected virtual object OnRequiredPropertyNotFound(string name) {
    throw new ConfigurationErrorsException(SR.GetString("Config_base_required_attribute_missing", new object[] { name }), this.PropertyFileName(name), this.PropertyLineNumber(name)); }

I'd suck it up and roll my own... but before you do that, Is it possible to have the system assume a default value for this configuration setting? I generally attempt to do that for every setting that might get missed bu Ops Management folk... (or perhaps I should say, for as many settings as possible - for some it is clearly not appropriate to have the system make a default decision...)

in general a custom exception is not a lot of effort... here's an example...

[Serializable]
public class MyCustomApplicationException : ApplicationException
{
    #region privates
    #endregion privates

    #region properties
    #endregion properties

    public MyCustomApplicationException (string sMessage,
        Exception innerException)
        : base(sMessage, innerException) { }
    public MyCustomApplicationException (string sMessage)
        : base(sMessage) { }
    public MyCustomApplicationException () { }

    #region Serializeable Code
    public MyCustomApplicationException (
       SerializationInfo info, StreamingContext context)
        : base(info, context) { }
    #endregion Serializeable Code
}

An alternative method you could use for your config files would be to use custom configuration sections as opposed to AppSettings. That way you can specify that a property IsRequired and the configuration system will handle this checking for you. If the property is missing it will throw a ConfigurationErrorsException so I suppose that supports the answer that you should use that exception in your case.


My general rule would be:

  1. If the case of the missing configuration is not very common and I believe I would never want to handle this case differently than other exceptions, I just use the basic "Exception" class with an appropriate message:

    throw new Exception("my message here")

  2. If I do want, or think there's a high probability I would want to handle this case in a different manner than most other exceptions, I would roll my own type as people have already suggested here.


I tend to disagree with the premise of your question:

In a nutshell, I need a standard exception that should be thrown when an application configuration setting is missing or contains an invalid value. You'd think the Framework had such an exception baked into it for applications to use. (It apparently did, but it was marked obsolete, and was replaced by something much larger in scope.)

According to the MSDN documentation on System.Exception (Exception Class, you really shouldn't be throwing exceptions for user input errors, for performance reasons (which has been pointed out by others on Stack Overflow and elsewhere). This seems to make sense as well - why can't your function return false if the user input is entered incorrectly, and then have the application gracefully exit? This seems to be more of a design problem then an issue with which Exception to throw.

As others have pointed out, if you really have to thrown an exception - for whatever reason - there isn't any reason why you couldn't define your Exception type by inheriting from System.Exception.


You could try inheriting off the XML Exception, or just using it.

참고URL : https://stackoverflow.com/questions/417187/net-which-exception-to-throw-when-a-required-configuration-setting-is-missing

반응형