Quantcast
Channel: ASP.NET Core Web API exception handling - Stack Overflow
Viewing all articles
Browse latest Browse all 13

Answer by pepa for ASP.NET Core Web API exception handling

$
0
0

If you want set custom exception handling behavior for a specific controller, you can do so by overriding the controllers OnActionExecuted method.

Remember to set the ExceptionHandled property to true to disable default exception handling behavior.

Here is a sample from an api I'm writing, where I want to catch specific types of exceptions and return a json formatted result:

    private static readonly Type[] API_CATCH_EXCEPTIONS = new Type[]    {        typeof(InvalidOperationException),        typeof(ValidationException)               };    public override void OnActionExecuted(ActionExecutedContext context)    {        base.OnActionExecuted(context);        if (context.Exception != null)        {            var exType = context.Exception.GetType();            if (API_CATCH_EXCEPTIONS.Any(type => exType == type || exType.IsSubclassOf(type)))            {                context.Result = Problem(detail: context.Exception.Message);                context.ExceptionHandled = true;            }        }      }

Viewing all articles
Browse latest Browse all 13

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>