1

I am learning exception handling in ASP.NET MVC, what I am trying to achieve is single custom error page that displays error with exception details which of course may varies depending, where is generated from. I not sure if on right track to start with! however I have C# code that read the SQL Stored procedure and return values, I want to add code-level exception handing i.e. try, catch and finally but want to display error on custom error page. How can I achieve this ??

public List<GetAllFunction_SP_Map> GetAllFunction_From_StoreProcedure()
    {  
            List<GetAllFunction_SP_Map> query;

            using (var dbContext = new FunctionContext())
            {
                query = dbContext.Database.SqlQuery<GetAllFunction_SP_Map>("exec GetAllFunction").ToList();
            }

            return query;      
}
2

2 Answers 2

1

Add Custom errors section in your web.config

<configuration>
    <system.web>
        <customErrors mode="RemoteOnly">
            <error statusCode="500"
                   redirect="~/Error/InternalServer" />
            <error statusCode="404"
                   redirect="~/Error/NotFound" />
        </customErrors>
    </system.web>
</configuration>

For the internal server error you can display the error message which is sent by ViewBag from your controller. So when you catch and exception, throw it again but set the message of the exception in your ViewBag. You can do some more work to display more friendly message, but log the error from the error page or from the point where the error occurs.

Sign up to request clarification or add additional context in comments.

Comments

1

[1]: Remove all 'customErrors' & 'httpErrors' from Web.config

[2]: Check 'App_Start/FilterConfig.cs' looks like this:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

[3]: in 'Global.asax' add this method:

public void Application_Error(Object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Server.ClearError();

    var routeData = new RouteData();
    routeData.Values.Add("controller", "ErrorPage");
    routeData.Values.Add("action", "Error");
    routeData.Values.Add("exception", exception);

    if (exception.GetType() == typeof(HttpException))
    {
        routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
    }
    else
    {
        routeData.Values.Add("statusCode", 500);
    }

    Response.TrySkipIisCustomErrors = true;
    IController controller = new ErrorPageController();
    controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
    Response.End();
}

[4]: Add 'Controllers/ErrorPageController.cs'

public class ErrorPageController : Controller
{
    public ActionResult Error(int statusCode, Exception exception)
    {
        Response.StatusCode = statusCode;
        ViewBag.StatusCode = statusCode + " Error";
        return View();
    }
}

[5]: in 'Views/Shared/Error.cshtml'

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = (!String.IsNullOrEmpty(ViewBag.StatusCode)) ? ViewBag.StatusCode : "500 Error";
}

 <h1 class="error">@(!String.IsNullOrEmpty(ViewBag.StatusCode) ? ViewBag.StatusCode : "500 Error"):</h1>


//@Model.ActionName
//@Model.ContollerName
//@Model.Exception.Message
//@Model.Exception.StackTrace

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.