2017-08-28 116 views
1

我有在获得自定义异常消息从我的Web API解决方案返回相当多的困难,覆盖异常消息。这是比这更复杂一些:如何处理ASP.NET Web API

enter image description here

我想用我自己的覆盖异常的只读属性:

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

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

不过,我也有一个全球性的异常处理程序:

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"); 

然后我抓住它像的方法:

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

我如何设置消息是“一些味精”?我想要做的是让api返回1-2个用例相关的错误消息,并将customErrors模式设置为on。

回答

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

你可以添加一个解释你的代码? – Alex

+0

这让我需要和我在一起,谢谢! – RandomUs1r