I think I know the answer, but is it possible to have the global.asax Application_Error event modify a textbox on the original page and not move the client to a different page? something like:
Exception exp = Server.GetLastError().GetBaseException();
System.Data.SqlClient.SqlException sqlex;
if (exp is System.Data.SqlClient.SqlException) {
sqlex = (System.Data.SqlClient.SqlException) exp;
if (sqlex.Number == 50000) {
if (HttpContext.Current.CurrentHandler is Page) {
Page p = (Page) HttpContext.Current.CurrentHandler;
Control c = p.FindControl("ErrorText");
if (c != null && c is Label) {
((Label) c).Text = exp.Message;
Server.ClearError();
return;
}
}
}
}
If you want to do this then you should use the "OnError" event of the page itself.
Related
I have an application that assigns a list of values to a DataGridView.
This is done inside a Try catch block.
Occasionally there is an issue with the with the procedure that produces this list (also in a try catch block) and this causes an error when the assignment is done.
It appears the exception is never caught by the block doing the assignment and the application freezes.
Is the exception handled inside the assignment call so that it is not propagated out to the catch block?
The exception produced as a pop up states
"The following exception occurred in the DataGridView:
System.IndexOutOfrangeException: Index 1 does not have a value at
System.Windows.Forms.dataGridViewDataConnection.GetError(Int32 rowIndex)
To replace this default dialog please handle the DataError event"
The code is basically
public void SetupRunners(EventDetails _eventDetails)
{
try
{
RunnerAssociates.Clear();
RunnerAssociates = null;
RunnerAssociates = createRunnerAssociateList(selectedEventDetails);
runnerAssociatesDataGridView.DataSource = RunnerAssociates;
runnerAssociatesDataGridView.DataMember = string.Empty;
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
}
private List<Runner_Associate> createRunnerAssociateList(EventDetails _meetAndRace) //NZRB_Global.MeetAndRace _meetAndRace)
{
const string methodName = "createRunnerAssociateList";
List<Runner_Associate> lra = new List<Runner_Associate>();
try
{
if (null != _meetAndRace)
{
_meetAndRace.UpdateAllProfiles();
foreach (RunnerDetail rd in _meetAndRace.runners.runnerList)
{
Runner_Associate ra = new Runner_Associate();
ra.Number = rd.number;
ra.RunnerName = rd.name;
RunnerProfile profile = rd.GetRunnerProfile();
if ((rbJockeyDriver.Checked) || (rbCustom.Checked))
{
ra.AssociateName = rd.person;
}
else if (profile != null)
{
if (rbTrainers.Checked)
{
ra.AssociateName = profile.trainer;
}
else if (rbOwners.Checked)
{
ra.AssociateName = profile.owners;
}
}
lra.Add(ra);
}
}
}
catch (Exception ex)
{
NZRB_Global.Utils.LogException(methodName, ex);
}
return lra;
}
Very odd one this - when i run some code on page_load and it fails, i want to populate a hidden text box with a value. The code fires and steps through in debug but the value still turns out blank. The code runs fine and hits this:
if (strResults[0] != "Success") {
fail.Value = "Failed";
}
so fail's value should say "Failed" if the submit was a failure (Success if it worked) but it doesn't.
Here' the code (edited)
try {
if (Request.QueryString["bla"] != null) {
if (Request.QueryString["blabla"] == "yes")
}
if (Request.QueryString["blablablabla"] != null) {
if (Request.QueryString["bla"] == "yes") {
string strResponse = "";
try {
if ());
if (intTransactionCodeAlreadyExists > 0) {
} else {
//do stuff
);
string[] strResults = strResponse.Split('|');
if (strResults[0] != "Success") {
fail.Value = "Failed";
}
}
}
} catch (Exception ex) {
//do stuff
}
}
}
} catch (Exception ex) {
//do stuff
}
This was a bit messed up in my setup. After a re-install of visual studio, the code started working as expected. Not 100% sure what the issue was here but all fixed. Thanks for the help.
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);
}
}
I'm getting the following exception:
System.Threading.ThreadAbortException: Thread was being aborted.
at System.Threading.Thread.AbortInternal() at
System.Threading.Thread.Abort(Object stateInfo) at
System.Web.HttpResponse.End() at
System.Web.HttpResponse.Redirect(String url, Boolean endResponse)
at System.Web.HttpResponse.Redirect(String url) at
taxi_selection.lnkbtnconfirm_Click(Object sender, EventArgs e)
I found that the solution for this is to use:
Response.Redirect("home.aspx",false);
but again this error is occurring.
What is a good solution for this?
my code snippets :
try
{
Decimal Amount = 0;
Int64 CabId = 0;
String CabName = "";
String CarImage = "";
foreach (DataListItem gr in dtlstcars.Items)
{
RadioButton objcheck = (RadioButton)gr.FindControl("rdbtncarchecked");
if (objcheck.Checked == true)
{
Literal ltrid = new Literal();
ltrid = (Literal)gr.FindControl("ltrid");
Label lbtaxiname = (Label)gr.FindControl("lbtaxiname");
Label lbonewaycarprice = (Label)gr.FindControl("lbonewaycarprice");
Label lbtwowaycarprice = (Label)gr.FindControl("lbtwowaycarprice");
Image imgcar = (Image)gr.FindControl("imgcar");
if (ltrid != null && lbtaxiname != null && imgcar != null && lbonewaycarprice != null && lbtwowaycarprice != null)
{
if (lbrootype.Text == "One")
{
Amount = Convert.ToDecimal(lbonewaycarprice.Text);
}
else
{
Amount = Convert.ToDecimal(lbtwowaycarprice.Text);
}
}
CabId = Convert.ToInt64(ltrid.Text);
CabName = lbtaxiname.Text;
CarImage = imgcar.ImageUrl;
}
}
if (lbroottype.Text != String.Empty && lbrouteid.Text != String.Empty && lbfrom.Text != String.Empty && lbpickupdate.Text != String.Empty && lbto.Text != String.Empty && lbpickupdate.Text != String.Empty && lbpickuptime.Text != String.Empty)
{
Session.Add("BookingDetail", BookingDetail(lbroottype.Text, Convert.ToInt64(lbrouteid.Text), lbfrom.Text, lbto.Text, Convert.ToDateTime(lbpickupdate.Text), lbpickuptime.Text, Convert.ToDateTime(lbreturndate.Text), String.Empty, CabId, CabName, CarImage, Amount, txtPickupaddress.Text, txtDropaddress.Text, txtlandmark.Text, txtname.Text, ddmobilestdcode.SelectedValue, txtmobileno.Text, ddalternatestdcode.SelectedValue, txtalternateno.Text, txtemail.Text, lbdays.Text));//3
Session.Remove("cart");
Session.Remove("editcart");
Response.Redirect("confirm");
}
else
{
Response.Redirect("home");
}
}
catch (Exception ext)
{
String msg = ext.Message;
da.InsertRecordWithQuery("insert error_tbl values('" + msg + "')");
}
http://support.microsoft.com/kb/312629
as you can see here the problem is that you are attempting to use response.redirect in a try/catch block. It thrown an exception.
Your solution of changing the call to be Response.Redirect(url, false) should work. You need to make sure to do it on every Response.Redirect call.
Also note that this will continue execution, so you will have to handle that (prevent it from continuing in some other way).
This is the way the Redirect works when you do not let the rest of the page continue to run. Its stop the thread and throw that abort exception. You can simple ignore it as:
try
{
Response.Redirect("newpage.aspx", true);
}
catch (System.Threading.ThreadAbortException)
{
// ignore it
}
catch (Exception x)
{
}
Attention
If you call the redirect with out stopping the rest of the processing, a hack that can stop the redirect process using a plugin like the NoRedirect can see your rest of the page .!
To prove my point here I make a question about : Redirect to a page with endResponse to true VS CompleteRequest and security thread
Response.Redirect without specifying the endResponse parameter as false (default is true) will call Response.End() internally and therefore will trigger a ThreadAbortException to stop execution.
One of two things are recommended here:
If you need to end the response, do not do it in a try/catch. This will cause the redirect to fail.
If you do not need to end the response, call this instead:
Response.Redirect(url, false);
Within try/catch:
try {
// do something that can throw an exception
Response.Redirect(url, false);
HttpContext.Current.ApplicationInstance.CompleteRequest();
} catch (SomeSpecificException ex) {
// Do something with the caught exception
}
To avoid postback handling and HTML rendering, you need to do more:
http://web.archive.org/web/20101224113858/http://www.c6software.com/codesolutions/dotnet/threadabortexception.aspx