gpt4 book ai didi

asp.net - 覆盖 Elmah 记录的错误消息

转载 作者:行者123 更新时间:2023-12-02 01:52:05 24 4
gpt4 key购买 nike

是否有任何方法可以覆盖 Elmah 记录的错误消息而不复制它?

我有一个自定义异常类:

public class BusinessException : Exception
{
// detailed error message used for logging / debugging
public string InternalErrorMessage { get; set; }

public BusinessException(string message, string internalMessage)
:base(message)
{
InternalErrorMessage = internalMessage;
}
}

从代码中,我抛出这样的异常:

string detailedErrorMessage = string.Format("User {0} does not have permissions to access CreateProduct resource", User.Identity.Name);
throw new BusinessException("Permission denied", detailedErrorMessage);

当 Elmah 记录错误时,它只记录 Permission denied 消息。但是,我需要记录异常的 InternalErrorMessage 属性。

我试图创建一个自定义的 HandleErrorAttribute 来执行此操作,但这会重复记录的异常:

public class ErrorHandleAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled == true)
return;

Exception exception = filterContext.Exception;

BusinessException businessException = exception as BusinessException;
if (businessException != null)
{
ErrorSignal.FromCurrentContext().Raise(new Exception(businessException.InternalErrorMessage, exception));
}
}
}

enter image description here

最佳答案

我认为您的问题可能出在这里:

    if (businessException != null) {
ErrorSignal.FromCurrentContext().Raise(
new Exception(businessException.InternalErrorMessage, exception));
}

当你创建一个新的异常而不是像这样的东西时:

    if (businessException != null) {
ErrorSignal.FromCurrentContext().Raise(businessException));
}

我已经完成了我的一个网站的代码,可以看看今天晚些时候我是否可以重现您的问题(假设这不起作用)。我认为这是帮助我实现的 SO 帖子:How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

编辑:

重新阅读您的问题和其他答案,我意识到我是在尝试解决您尝试的更正而不是实际问题。你试过类似this solution的东西吗?这与您当前的尝试仅略有不同:

public override void OnException(ExceptionContext filterContext) {
if (filterContext.ExceptionHandled == true) {
return;
}
Exception exception = filterContext.Exception;

BusinessException businessException = exception as BusinessException;
if (businessException != null) {
var customEx = new Exception(
businessException.InternalErrorMessage, new BusinessException());
ErrorSignal.FromCurrentContext().Raise(customEx);
return;
}
}

检查 InternalErrormessage 是否返回您期望的内容,我希望在此处强制执行 return 将防止异常被记录两次。否则,它本质上就是您所做的。

关于asp.net - 覆盖 Elmah 记录的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22192205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com