locked
asp.net MVC5 redirect to custom error page if LINQ query returns null/empty RRS feed

  • Question

  • User1571524970 posted

    I have some logic in a class which uses various LINQ queries. I would like to redirect the user to a customer error page which is in Views > shared > CustomError.cshtml, if any of the LINQ queries return null. What is the easiest way to set this up in MVC5?

    Same of the code that includes a LINQ query:

    public void AddQ2Answer(SurveyCheckboxCollections checkboxes, int id)
            {
                using (var db = new RDSContext())
                {
                    // *** redirect user to custom error page if s1 == null/empty
                    var s1 = db.SecondarySchoolSurveys.FirstOrDefault(s => s.Id == id);
    
                    CheckboxData q2Male = checkboxes.SecondarySchoolCheckboxes["Q2Male"];
                    CheckboxData q2Female = checkboxes.SecondarySchoolCheckboxes["Q2Female"];
                    CheckboxData q2Other = checkboxes.SecondarySchoolCheckboxes["Q2Other"];
                    CheckboxData q2DontWantToSay = checkboxes.SecondarySchoolCheckboxes["Q2DontWantToSay"];
    
                    //numbers of checkboxes marked for validation
                    int checkboxValidaiton = 0;
    
                    //update SecondarySchoolSurvey checkbox answers in database with IsChecked values from checkbox dictionary 
                    if (q2Male.IsChecked)
                    {
                        s1.Q2 = Gender.Male;
                        checkboxValidaiton++;
                    }
                    if (q2Female.IsChecked)
                    {
                        s1.Q2 = Gender.Female;
                        checkboxValidaiton++;
                    }
                    if (q2Other.IsChecked)
                    {
                        s1.Q2 = Gender.Other;
                        checkboxValidaiton++;
                    }
                    if (q2DontWantToSay.IsChecked)
                    {
                        s1.Q2 = Gender.None;
                        checkboxValidaiton++;
                    }
    
                    //validate only 1 checkbox has been marked 
                    if (checkboxValidaiton == 0)
                    {
                        s1.Flag = true;
                        s1.FlagContent += "| Question2: no checkboxes marked. ";
                    }
                    else if (checkboxValidaiton > 1)
                    {
                        s1.Flag = true;
                        s1.FlagContent += "| Question2: more than 1 checkboxes marked. ";
                    }
    
                    db.SaveChanges();
                }
            }

    I have also turned custom errors on in web.config:

    <system.web>
       <customErrors mode="On" />
    </system.web>

    Saturday, April 25, 2020 5:19 PM

Answers

  • User1120430333 posted

    You could implement a Basecontroller that catches all unhandled exceptions. You can throw the exception and the BaseController will catch the exception. I don't have any try/catches in any controller or in any code the controller references like a classlib project, because all exceptions are unhandled an caught by the Basecontroller. I make a little adjustment to the Basecontroller in the Link

    https://www.code-sample.com/2014/08/base-controller-in-mvc-5.html

    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using log4net;
    
    namespace MVC.Controllers
    {
        public abstract partial class BaseController : Controller
        {
            private ILog _logger;
    
            protected BaseController()
            {
                _logger =  LogManager.GetLogger(typeof(BaseController));
            }
    
            protected override void OnException(ExceptionContext filterContext)
            {
                AppException appException = new AppException(Convert.ToString(filterContext.Exception))
                {
                    Type = filterContext.GetType().ToString(),
                    StackTrace = filterContext.Exception.StackTrace,
                    Source = filterContext.Exception.Source,
                    InnerException = Convert.ToString(filterContext.Exception.InnerException)
                };
    
                _logger.Error(appException.ToString());
    
                Server.ClearError();
    
                RedirectToControllers("Home", "Error");
            }
    
            private void RedirectToControllers(string control, string action)
            {
                var routeData = new RouteData();
    
                routeData.Values["controller"] = control;
    
                routeData.Values["action"] = action;
    
                IController controller = new HomeController();
    
                ((IController) controller).Execute(new RequestContext(
                    new HttpContextWrapper(System.Web.HttpContext.Current), routeData));
            }
        }
    }
    namespace MVC
    {
        using System;
    
        public class AppException : Exception
        {
            public AppException(String message) : base(message)
            { }
    
            public string Type { get; set; }
            public string StackTrace { get; set; }
            public string InnerException { get; set; }
            public AppException(String message, Exception inner) : base(message, inner) { }
        }
    
    }
    sing System.Web.Mvc;
    using MVC.Models;
    
    namespace MVC.Controllers
    {
        [Authorize]
        public class StudentsController : BaseController  
        {
            private IStudentModels studmods;
            public StudentsController(IStudentModels studentModels)
            {
                studmods = studentModels;
            }
    
            // GET: Students
    
            [AllowAnonymous]
            public ActionResult Index()
            {
                return View(studmods.GetStudents());
            }
    }
    // rest of code removed for brevatity 
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MVC.Controllers
    {
        public class HomeController : BaseController
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult Error()
            {
                //  var feature = this.HttpContext.f.Features.Get<IExceptionHandlerFeature>();
                return View("~/Views/Shared/Error.cshtml", null);
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, April 25, 2020 6:19 PM

All replies

  • User1120430333 posted

    You could implement a Basecontroller that catches all unhandled exceptions. You can throw the exception and the BaseController will catch the exception. I don't have any try/catches in any controller or in any code the controller references like a classlib project, because all exceptions are unhandled an caught by the Basecontroller. I make a little adjustment to the Basecontroller in the Link

    https://www.code-sample.com/2014/08/base-controller-in-mvc-5.html

    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using log4net;
    
    namespace MVC.Controllers
    {
        public abstract partial class BaseController : Controller
        {
            private ILog _logger;
    
            protected BaseController()
            {
                _logger =  LogManager.GetLogger(typeof(BaseController));
            }
    
            protected override void OnException(ExceptionContext filterContext)
            {
                AppException appException = new AppException(Convert.ToString(filterContext.Exception))
                {
                    Type = filterContext.GetType().ToString(),
                    StackTrace = filterContext.Exception.StackTrace,
                    Source = filterContext.Exception.Source,
                    InnerException = Convert.ToString(filterContext.Exception.InnerException)
                };
    
                _logger.Error(appException.ToString());
    
                Server.ClearError();
    
                RedirectToControllers("Home", "Error");
            }
    
            private void RedirectToControllers(string control, string action)
            {
                var routeData = new RouteData();
    
                routeData.Values["controller"] = control;
    
                routeData.Values["action"] = action;
    
                IController controller = new HomeController();
    
                ((IController) controller).Execute(new RequestContext(
                    new HttpContextWrapper(System.Web.HttpContext.Current), routeData));
            }
        }
    }
    namespace MVC
    {
        using System;
    
        public class AppException : Exception
        {
            public AppException(String message) : base(message)
            { }
    
            public string Type { get; set; }
            public string StackTrace { get; set; }
            public string InnerException { get; set; }
            public AppException(String message, Exception inner) : base(message, inner) { }
        }
    
    }
    sing System.Web.Mvc;
    using MVC.Models;
    
    namespace MVC.Controllers
    {
        [Authorize]
        public class StudentsController : BaseController  
        {
            private IStudentModels studmods;
            public StudentsController(IStudentModels studentModels)
            {
                studmods = studentModels;
            }
    
            // GET: Students
    
            [AllowAnonymous]
            public ActionResult Index()
            {
                return View(studmods.GetStudents());
            }
    }
    // rest of code removed for brevatity 
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MVC.Controllers
    {
        public class HomeController : BaseController
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult Error()
            {
                //  var feature = this.HttpContext.f.Features.Get<IExceptionHandlerFeature>();
                return View("~/Views/Shared/Error.cshtml", null);
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, April 25, 2020 6:19 PM
  • User1571524970 posted

    Perfect. Thanks a lot!

    Saturday, April 25, 2020 6:23 PM