Good day to all! Trying to solve a problem. I use a method that handles all errors on the site (This method found on the blog of one man)
Global.asax
protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
Exception ex = ctx.Server.GetLastError();
ctx.Response.Clear();
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
IController controller = new CategoryController();
var context = new ControllerContext(rc, (ControllerBase)controller);
var viewResult = new ViewResult();
var httpException = ex as HttpException;
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
viewResult.ViewName = "Error404";
break;
case 500:
viewResult.ViewName = "Error500";
break;
default:
viewResult.ViewName = "Error";
break;
}
}
else
{
viewResult.ViewName = "Error";
}
viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action"));
viewResult.ExecuteResult(context);
ctx.Server.ClearError();
}
When I start Projects in the studio, causing the error. I get exception at that code:
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
Exception:
Unable to cast object of type 'System.Web.DefaultHttpHandler' to type 'System.Web.Mvc.MvcHandler'
Once I stop debugging (Shift + F5). This method works well and handles any errors. But at the start of project, causing the error. Looking for a solution to these topics, but this problem is not found. Help please.
[HandleError]
public class CategoryController : Controller
{
// some methods
}
Solved his problem by using code:
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
{
Response.Redirect("~/Error/404");
}
else
{
Response.Redirect("~/Error/Other");
}
Server.ClearError();
}
Related
I'm developing ASP.Net application and I'm currently struggling with exception handling. I've already managed to do proper exception handling but I don't really know how to handle internal errors that are not suitable for UI.
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
LogManager.GetCurrentClassLogger().Error(ex);
Response.Clear();
HttpException httpEx = ex as HttpException;
if (httpEx == null)
{
switch(ex.GetType())
{
//Convert ex into httpexception
//with statuscode that depends on the exception type
}
}
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Handler");
routeData.Values.Add("exception", httpEx);
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
var c = ControllerBuilder.Current.GetControllerFactory().CreateController(rc, "Error");
c.Execute(rc);
}
Instead of trying to cast your exception to a HttpException just try to create a new HttpException with the original exception as the inner one:
HttpException httpEx = new HttpException(500, msg, ex);
I have read many articles now about how to handle errors in asp.net, and I think it is a lot of information to take in.
I'm using service layer pattern, and in my service model, I have the following code:
public List<SpotifyAlbumModel> AddSpotifyAlbums(List<SpotifyAlbumModel> albums)
{
try
{
if(albums != null)
{
ctx.SpotifyAlbums.AddRange(albums);
ctx.SaveChanges();
}
return albums;
}
catch(Exception e)
{
throw new Exception();
}
}
If a problem rises, I want to redirect the user to a error page that says something went wrong.
I call my service method from my controller:
public ActionResult AddSpotifyAlbums(List<SpotifyAlbumModel> albums)
{
_profileService.AddSpotifyAlbums(albums);
return Json(new { data = albums });
}
How can I determine in my controller method if something went wrong in the service, and then redirect the user to the error page?
Or should I have a global errorHandler that transfer the user as soon a excetion is caught?
You can add Application_Error method in global.asax. For example:
void Application_Error(Object sender, EventArgs e)
{
var exception = Server.GetLastError();
if (exception == null) {
return;
}
// Handle an exception here...
// Redirect to an error page
Response.Redirect("Error");
}
We've tried multiple things, but what seems to work best is to just handle every exception yourself. We didn't completely invent this yourself, the inspiration was from here:
ASP.NET MVC 404 Error Handling
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 404)
{
Log.Debug("Application_EndRequest:" + Context.Response.StatusCode + "; Url=" + Context.Request.Url);
Response.Clear();
string language = LanguageUtil.Instance.MapLanguageCodeToWebsiteUrlLanguage(HttpContext.Current.Request, Thread.CurrentThread.CurrentUICulture.Name);
var rd = new RouteData();
//rd.DataTokens["area"] = "AreaName"; // In case controller is in another area
rd.Values["languageCode"] = language;
rd.Values["controller"] = "Error404";
rd.Values["action"] = "Index";
Response.TrySkipIisCustomErrors = true;
IController c = new Controllers.Error404Controller();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
}
else if (Context.Response.StatusCode == 500)
{
Log.Debug("Application_EndRequest:" + Context.Response.StatusCode + "; Url=" + Context.Request.Url);
Response.Clear();
string language = LanguageUtil.Instance.MapLanguageCodeToWebsiteUrlLanguage(HttpContext.Current.Request, Thread.CurrentThread.CurrentUICulture.Name);
Response.Redirect("~/" + language + "/error");
}
}
We have strange situation where something is causing an exception on Http.Current object such as .Response or .Request. The exception is NullReferecne. I was under the impression that HTTPContext under normal circumstances can't be null. But since in our case it can how should I handle this type of exception? We're already handle HTTPException in Global.asax.cs and with ErrorSeverity as Fatal which is home grown class. I 've modified the code that checks for null value but I'm not cetain if that really catches this scenario - see code below:
protected void Application_Error(object sender, EventArgs e)
{
try
{
Exception exception = Server.GetLastError();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
if (httpException.GetHttpCode() == 404)
{
return;
}
}
string errMessage = "Running Application_Error. An unhandled error occured in the application.";
errMessage = errMessage + "Error message = " + exception.Message;
//This is the IF-ELSE I've added but it just doesn't "feel right"
if (HttpContext.Current.Request != null || HttpContext.Current.Response != null)
{
StaticServices.ErrorLogger.LogSingleException(exception, ErrorSeverity.Fatal);
}
else
{
StaticServices.ErrorLogger.LogSingleException(exception, ErrorSeverity.Info);
}
exception = exception.InnerException;
while (exception != null)
{
StaticServices.ErrorLogger.LogSingleException(exception, ErrorSeverity.Fatal);
exception = exception.InnerException;
}
QSession session = QSession.GetInstance();
bool mobileIndicator = session != null ? session.Packet.QPolicy.IsMobileApplication : false;
if (mobileIndicator)
{
LogAndRedirectTechDiff("MobileTechnicalDifficulties.htm", session != null);
}
else
{
//This is the IF-ELSE I've added but it just doesn't "feel right"
if (HttpContext.Current.Request != null || HttpContext.Current.Response != null)
{
LogAndRedirectTechDiff("TechnicalDifficulties.htm", session != null);
}
else
{
LogAndRedirectTechDiff("UnsupportedBrowser.htm", session != null);
}
}
}
catch (Exception ex)
{
EventLog.WriteEntry("FQ",
"Global.asax.cs Application_Error method caused an exception. This is the error message :" +
ex.ToString(), EventLogEntryType.Error);
}
}
How should I handle those exceptions that I can't catch in the C# code behind... like for example I am facing failed email sending system.Net.Sockets.SocketException but I have no chance to handling the page codebhind.. where should I handle it?
protected void CreateUserWizard1_SendingMail1(object sender, MailMessageEventArgs e)
{
string emailname="";
try
{
TextBox textboxemail = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email");
MembershipUser user = Membership.GetUser(textboxemail.Text);
Guid userid = (Guid)user.ProviderUserKey;
string verificationurl = "http://www.spiralsnet.com/Login.aspx?NewUserId=" + userid.ToString();
e.Message.IsBodyHtml = true;
e.Message.From = new System.Net.Mail.MailAddress("SpiralsWhirls#yahoo.com", "SpiralsNet");
e.Message.Body = e.Message.Body.Replace("<%VU%>", verificationurl);
}
catch (System.Net.Sockets.SocketException ex)
{
Membership.DeleteUser(emailname);
}
}
I'm currently having problem in my project. I'm having Code 4004 error in silverlight application. I don't know what I did wrong. Here are the image link.
http://s1100.photobucket.com/user/Fredi_Tansari/media/errorInsilverlight.png.html
here are the codes. After the the invalideoperation exception it goes to the unhandled exception error.
private void getstatusCompleted(LoadOperation<PatientStatus1> obj)
{
try
{
PatientStatus1 bc = obj.Entities.First();
if (bc != null)
{
MessageBox.Show("Patient has a status already, please use update instead new");
return;
}
else
{
MessageBox.Show("inserting new Patient status");
}
}
catch (InvalidOperationException e)
{
PatientStatus1 newPatientStatus = new PatientStatus1();
newPatientStatus.ColorCodeID = "1";
newPatientStatus.timestamp = DateTime.Now;
newPatientStatus.UserID = "Jimmi";
newPatientStatus.Patient_PatientID = Convert.ToInt32(patientIDTextBox.Text);
newPatientStatus.MasterPatientStatus_masterPatientStatusId = Convert.ToInt32(masterPatientStatusIdTextBox.Text);
newPatientStatus.MasterLocation_masterLocationID = Convert.ToInt32(masterLocationIDTextBox1.Text);
patientstatusDomainContext.PatientStatus1s.Add(newPatientStatus);
patientstatusDomainContext.SubmitChanges();
}
}
Thanks in advance for the help
Try to set this key value to 1.
HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug