I have a website in C# MVC and I want to add a feature to it, i.e, to save all the errors in database using one function only, I can place try
/catch
block in every method of the web applications but it would be lengthy process, so is it possible to place a method/code in one place from where I can save each and every error in database??
I have no idea
Thank you for asking a question here.
You can place this method in Global.asax which will be executed, whenever error occurs in application
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
string action;
switch (httpException.GetHttpCode())
{
case 404:
// page not found
action = "HttpError404";
break;
case 500:
// server error
action = "HttpError500";
break;
default:
action = "General";
break;
}
// clear error on server
Server.ClearError();
//Save error details in database
using (var context = new DatabseCOnnection())
{
var Error = new ErrorDetail();
Error.ErrorMessage = exception.Message;
context.ErrorDetails.Add(Error);
context.SaveChanges();
}
//Redirect to ErrorController method based on error type
Response.Redirect(String.Format("~/Error/{0}", action));
}
}
that's it
You might also like to add Custom Error pages to show a user a friendly error message in MVC, so here is the article for it : https://qawithexperts.com/article/asp-net/custom-error-pages-in-aspnet-mvc/242
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly