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
}
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With