2017-08-28 9 views
1

私のWeb APIソリューションから返されるカスタム例外メッセージを取得するのにかなりの困難があります。これは、もう少し複雑なものよります:ASP.NET Web APIの例外メッセージをオーバーライドする方法

public class CustomException : Exception 
{ 
    public CustomException(string message) 
     : base(message) 
    { 
    } 

    public CustomException(string message, Exception inner) 
     : base(message, inner) 
    { 
    } 
} 

しかし、私はまた、グローバルな例外ハンドラを持っている:

enter image description here

は、私は自分で例外の読み取り専用のプロパティをオーバーライドしたい

public class GlobalExceptionLogger : ExceptionLogger 
{ 
    public override void Log(ExceptionLoggerContext context) 
    { 
     if (context.Exception.Message == "Password has already been used in the past...1") 
     { 
      throw new CustomException("some msg", context.Exception); 
     } 

     NLogger.LogError("Global Error Handler", context.Exception); 
    } 
} 

私はそうのように私はエラーをスロー:

if (some condition)) throw new CustomException("some msg"); 

そして私のような方法でそれをキャッチ:私はメッセージを設定することができ、「いくつかのMSG」になる方法

catch (CustomException ex) 
{ 
    throw ex; 
} 
catch (Exception ex) 
{ 
    NLogger.LogError(ex); 
    throw; 
} 

?私がしようとしているのは、apiがcustomErrorsモードをonに設定している場合の、1-2のユースケース関連のエラーメッセージを返すようにすることです。

答えて

0
throw new HttpResponseException(
    new HttpResponseMessage 
    { 
     StatusCode = code, 
     ReasonPhrase = phrase, 
     Content = new StringContent(body) 
    }); 
+2

コードに説明を追加できますか? – Alex

+0

それは私がこれと一緒にいる必要があるところに私を得ました、ありがとう! – RandomUs1r

関連する問題