Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExceptionFilter difference between OnExceptionAsync vs.OnException

That's it.

When writing custome exception filter in MVC or WebApi, what is the difference between OnExceptionAsync and OnException methods? Is it so that OnExceptionAsync is called only when using asynchronous controllers? Or both are called?

When to use which?

How to use OnExceptionAsync which returns task result?

Some base code to ilustrate:

public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        //TODO exception handling
    }

    public override Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
    {
        //TODO exception handling
    }
}
like image 793
Juri Avatar asked Jul 30 '14 07:07

Juri


People also ask

What is the exception filter in asp net core?

Exception filters apply global policies to unhandled exceptions that occur before the response body has been written to. Result filters: Run immediately before and after the execution of action results. Run only when the action method executes successfully.

What is exception filter?

Exception Filter provides an ability to handle the exception for all the method, controller classes in one place. Exception filters execute when some of the exceptions are thrown from an action. The exception can be anything. This is by creating a class that inherits from IExceptionFilter and FileAttribute interface.


1 Answers

I think OnExceptionAsync is used with async Actions.

If you want a simple scenario like sending a serializable description of the error, you can override OnException and not OnExceptionAsync, since OnExceptionAsync invokes OnException in the ExceptionFilterAttribute default implementation:

public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
{
    actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, new 
    {
        Message = "An unexpected error has occured",
        Description = actionExecutedContext.Exception.Message
    });

    actionExecutedContext.Response.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue()
    {
        NoCache = true,
        NoStore = true
    };
}

But you may want to log the exception in a database and take advantage of the async behavior :

public override async Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
    await LogException(actionExecutedContext.Exception);
}

The async and await keywords will do the job for you to manage the async behavior. You don't need to return the Task object.

like image 94
Loic Avatar answered Oct 08 '22 15:10

Loic