ExceptionFilter stack trace in synchronous action scenario

孤街浪徒 提交于 2019-12-06 16:36:06

If you are forced to not upgrade Web API packages, then you best option is probably to avoid using ActionFilters for handling exceptions at all.

A better (and global) approach would be to create an ExceptionHandler to replace the default implementation inside the Web API configuration:

public class MyExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var ex = context.Exception;

        //log exception, do stuff

        context.Result = new InternalServerErrorResult(context.Request);
    }

    public override bool ShouldHandle(ExceptionHandlerContext context)
    {
        bool shouldHandle;

        //logic to check if you should handle the exception or not

        return shouldHandle;
    }
}

And inside WebApiConfig.cs (assuming config is your HttpConfiguration object):

config.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler());

If you, instead, only want to log the exception (and not handling it in some way), then you could implement an ExceptionLogger in a similar way:

public class MyExceptionLogger : ExceptionLogger
{
    public override void Log(ExceptionLoggerContext context)
    {
        MyLogger.Log(LogLevel.Error, context.Exception, "some message");
    }
}

And again:

config.Services.Replace(typeof(IExceptionLogger), new MyExceptionLogger());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!