我从Web Api解决方案中获取自定义异常消息时遇到了一些困难。它有点复杂:
我想用我自己的覆盖异常的只读属性:
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 :(得分:0)
throw new HttpResponseException(
new HttpResponseMessage
{
StatusCode = code,
ReasonPhrase = phrase,
Content = new StringContent(body)
});