如何覆盖 ASP.NET Web API 中的异常消息
How to override exception message in ASP.NET Web API
我很难从我的 Web Api 解决方案中获取到 return 的自定义异常消息。比这复杂一点:
我想用我自己的异常覆盖只读 属性:
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;
}
如何将消息设置为 "some msg"?我想要做的是将 api return 1-2 个与用例相关的错误消息与 customErrors 模式设置为开。
throw new HttpResponseException(
new HttpResponseMessage
{
StatusCode = code,
ReasonPhrase = phrase,
Content = new StringContent(body)
});
我很难从我的 Web Api 解决方案中获取到 return 的自定义异常消息。比这复杂一点:
我想用我自己的异常覆盖只读 属性:
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;
}
如何将消息设置为 "some msg"?我想要做的是将 api return 1-2 个与用例相关的错误消息与 customErrors 模式设置为开。
throw new HttpResponseException(
new HttpResponseMessage
{
StatusCode = code,
ReasonPhrase = phrase,
Content = new StringContent(body)
});