0
votes

In my api I have a standard Controller containing an action, the action calls onto a service which then calls onto client to contact other third party api's.

I'm looking to implement an exception filter something similar to:

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    private readonly IHostingEnvironment _hostingEnvironment;
    private readonly IModelMetadataProvider _modelMetadataProvider;

    public CustomExceptionFilterAttribute(
        IHostingEnvironment hostingEnvironment,
        IModelMetadataProvider modelMetadataProvider)
    {
        _hostingEnvironment = hostingEnvironment;
        _modelMetadataProvider = modelMetadataProvider;
    }

    public override void OnException(ExceptionContext context)
    {
        if (!_hostingEnvironment.IsDevelopment())
        {
            // do nothing
            return;
        }
        var result = new ViewResult {ViewName = "CustomError"};
        result.ViewData = new ViewDataDictionary(_modelMetadataProvider,context.ModelState);
        result.ViewData.Add("Exception", context.Exception);
        // TODO: Pass additional detailed data via ViewData
        context.Result = result;
    }
}

If my client class for example threw an exception would the filter get called immediately even though my service class which calls the client class had a try catch ready to catch such an exception?

1
please provide some code. - Daniel A. White
I'll add the exact same code as linked in the question. I thought that was enough. - eVolve
im not sure what your asking. - Daniel A. White
I dont think it could be any clearer based off the last two lines in the question. - eVolve
please provide a minimal reproducible example. who is client? - Daniel A. White

1 Answers

1
votes

No. Per the documentation you refer to, the exception filter will only be triggered by unhandled exceptions; if the client exception is handled by the service and isn't rethrown, the exception filter will not fire.

Exception filters:

  • Don't have before and after events.
  • Implement OnException or OnExceptionAsync.
  • Handle unhandled exceptions that occur in controller creation, model binding, action filters, or action methods.
  • Do not catch exceptions that occur in Resource filters, Result filters, or MVC Result execution.