ASP.NET MVC application Controller methods are different:

  • Return a JSON response, for example {status: 0 , message: "Data saved successfully"}
  • Return JSON in javascript datatables.net library format

There can be two types of errors:

  • Error in business logic: incorrect data came from the user and he needs to return the following JSON: {status: 1 , message: "Date not specified ..."}
  • System error (incorrect SQL query, loss of communication with the database, other runtime error) - in this case, the user needs to return JSON {status: 1 , message: "Something went wrong, try later"}, and save details of the exception to log file (possibly with sending a message to the administrator)

It would not be desirable in the code of controllers to scatter try-catch, there is the idea of ​​data validation errors throwing exceptions, catching them and system errors in one place.

Is it possible to implement this with filters or something else?

    1 answer 1

    Yes, it can be done. It is necessary to implement the IExceptionFilter interface and apply the resulting class to the required controllers. Here is a link to the article with examples and descriptions: Exception Filters

    If necessary, you can apply the filter globally. Example:

    using System.Web.Mvc; namespace WebApp2.Config { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new RangeExceptionAttribute()); } } } 

    This code is called from Global.asax

     public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); // Другая инициализация. } } 

    Inside the OnException handler, you can parse the exception and take the necessary action. If you need to implement a different logic of reaction to different exceptions, you can add several filters.