locked
How to handle errors in API Controller in MVC RRS feed

  • Question

  • User-1188570427 posted

    Hello,

    What is the "proper" way of handling errors in a MVC application for a API Controller?

    I have this implemented: https://www.c-sharpcorner.com/article/exception-handling-in-asp-net-web-api/

    But on our other controllers I can just inherit from a : BaseController as the below:

        /// <summary>
        /// Base Controller
        /// </summary>
        /// <seealso cref="Controller" />
        public abstract partial class BaseController : Controller
        {
            /// <summary>
            /// Called when an unhandled exception occurs in any action. Will log to the database.
            /// </summary>
            /// <param name="filterContext">Information about the current request and action.</param>
            protected override void OnException(ExceptionContext filterContext)
            {
    
    
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.ExceptionHandled = true;
                    filterContext.Result = new JsonResult
                    {
                        Data = new { success = false, errorMessage = "An error has occurred and has been logged. Please contact an administrator if the issue persists." },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
    
                    base.OnException(filterContext);
                }
            }
        }

    I do not like how I have to add an attribute to the top of the class of each API Controller though.

    Is there a better way or the way I have it implemented is OK?

    Thursday, September 12, 2019 1:11 PM

Answers

  • User-474980206 posted
    I prefer return an error status code, otherwise the client has to handle 2 types of errors. One network, or server error that return status code, and the ok status with an error node.
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 12, 2019 2:06 PM
  • User-1188570427 posted

    I prefer return an error status code, otherwise the client has to handle 2 types of errors. One network, or server error that return status code, and the ok status with an error node.

    Thanks.

    Here is my final answer:

        public static class WebApiConfig
        {
            /// <summary>
            /// Registers the specified configuration.
            /// </summary>
            /// <param name="config">The configuration.</param>
            public static void Register(HttpConfiguration config)
            {
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional });
    
                config.Filters.Add(new APICustomExceptionFilter());
            }
        }

    I was able to register it ONCE in my Register method of my WebAPIConfig.

    This will do the trick so I do not have to decorate it on each API Controller in my application.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 13, 2019 2:40 AM

All replies

  • User-474980206 posted
    I prefer return an error status code, otherwise the client has to handle 2 types of errors. One network, or server error that return status code, and the ok status with an error node.
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 12, 2019 2:06 PM
  • User-1188570427 posted

    I prefer return an error status code, otherwise the client has to handle 2 types of errors. One network, or server error that return status code, and the ok status with an error node.

    Thanks.

    Here is my final answer:

        public static class WebApiConfig
        {
            /// <summary>
            /// Registers the specified configuration.
            /// </summary>
            /// <param name="config">The configuration.</param>
            public static void Register(HttpConfiguration config)
            {
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional });
    
                config.Filters.Add(new APICustomExceptionFilter());
            }
        }

    I was able to register it ONCE in my Register method of my WebAPIConfig.

    This will do the trick so I do not have to decorate it on each API Controller in my application.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 13, 2019 2:40 AM