Append To Text File Each Error - c#

I am using this syntax to write errors to a text file for logging in my Global.axax - it overwrites each time and only logs the most recent error. While this is helpful, it is not as helpful as I need it to be. How can I log each error that is raised?
This is my current code that only logs the most recent:
void Application_Error(object sender, EventArgs e)
{
Exception CurrentException = Server.GetLastError();
Server.ClearError();
if (CurrentException != null)
{
try
{
using (StreamWriter sw = new StreamWriter(Server.MapPath("HereAreErrors.txt")))
{
sw.WriteLine(CurrentException.ToString());
sw.Close();
}
}
catch (Exception ex) { }
}
}

As others have stated you're better off using an existing log tool to handle your logging. They have a myriad of features and, best of all, are maintained by someone else!
With that said, and in the interest of answering the question as asked, here's how to resolve your problem. It has the added benefit of creating the file if it doesn't exist.
void Application_Error(object sender, EventArgs e)
{
Exception CurrentException = Server.GetLastError();
Server.ClearError();
if (CurrentException != null)
{
try
{
File.AppendAllText(Server.MapPath("HereAreErrors.txt"), CurrentException.ToString());
}
catch (Exception ex) { }
}
}

Related

ASP.NET: Only catch certain errors at page level?

Looking at:
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/aspnet-error-handling
and specifically:
private void Page_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError();
// Handle specific exception.
if (exc is HttpUnhandledException)
{
ErrorMsgTextBox.Text = "An error occurred on this page. Please verify your " +
"information to resolve the issue."
}
// Clear the error from the server.
Server.ClearError();
}
Is there a way to only handle asp.net file uploader file size too big (e.g. over 50MB) and let all other errors be handled at the application level?
BTW, here is code to catch files that are too big at the application level:
//Global.asax
private void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError();
var httpException = ex as HttpException ?? ex.InnerException as HttpException;
if(httpException == null) return;
if (((System.Web.HttpException)httpException.InnerException).WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
{
//handle the error
Response.Write("Too big a file, dude"); //for example
}
}
So in other words, can we "throw" an application level error from a page level error method (e.g., when it's anything other than that file size exception that we want to handle on that specific page)?

Generating custom exception in c#

I have tried this code to raise a manual exception
protected void test ()
try
{
throw new Exception("HI"); //line22
}
catch (Exception ex) { lblerror.Text = ex.ToString(); }
but received exception below
System.ArgumentException: HI at
Project_Test_M_Test.btnsubmit_Click(Object sender, EventArgs e) in
D:\Project\Test\M_Test.aspx.cs:line 22
I want to see error message that I have send not this.
Please use ex.Message instead of ex.ToString().
btw, its not a good idea to throw the base class Exception. please use a more specific one.
This is what you need to do, use Message property to access the error message.
protected void test ()
{
try
{
throw new Exception("HI"); // Exception message passed from constructor
}
catch (Exception ex)
{
lblerror.Text = ex.Message;
}
}

Umbraco back office save validation

In Umbraco V7 how to show custom error validation message on back office save or publish to user
I have tried following but it shows 'Publishing was cancelled by a 3rd party plugin' not actual error message
void ContentService_Saving(IContentService sender, SaveEventArgs<IContent> e)
{
e.Cancel = true;
ShowErrorBubble("Error saving item", "Error:duplicate records exists");
}
private static void ShowErrorBubble(string title, string exception)
{
try
{
umbraco.BasePages.UmbracoEnsuredPage.Current.ClientTools.ShowSpeechBubble(umbraco.BasePages.UmbracoEnsuredPage.speechBubbleIcon.error, title, exception);
}
catch (Exception ex)
{
//do nothing at the moment, forums suggest we cannot send an error message
}
}
That's an old snippet you're using. It never worked properly that way anyhow. Try this code instead:
void ContentService_Saving(IContentService sender, SaveEventArgs e)
{
ShowErrorBubble(e, "Error saving item", "Error:duplicate records exists");
}
private static void ShowErrorBubble(SaveEventArgs e, string title, string text)
{
try
{
e.Messages.Add(new Umbraco.Core.Events.EventMessage(title, text, Umbraco.Core.Events.EventMessageType.Warning));
e.Cancel = true;
}
catch (Exception ex)
{
//do nothing at the moment, forums suggest we cannot send an error message
}
}

Catch all exceptions in ASP.NET C# rather than each method in a `try{} catch{}` block

Is there a better way to catch all exceptions in one place without writing try{} catch{} for each method?
You can catch the exceptions in your application by overwriting Application_Error found in Global.asax. However, using this approach you cannot act on these exceptions like you could using a regular try catch block.
You can log it
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// if there's an Inner Exception we'll most likely be more interested in that
if (ex .InnerException != null)
{
ex = ex .InnerException;
}
// filter exception using ex.GetType() ...
// log exception ...
// Clear all errors for the current HTTP request.
HttpContext.Current.ClearError();
}
And/or redirect
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// process exception
// redirect
HttpContext.Current.ClearError();
Response.Redirect("~/Error.aspx", false);
return;
}
And this is about all your can do.
Thanks All. I got an answer from a site.Here is the code i have modified according to the exception and logging errors with a third party(Elmah) in the application. Hope, it will be helpful for others.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
//Get the exception object
Exception exceptionObject = Server.GetLastError();
try
{
if (exceptionObject != null)
{
if (exceptionObject.InnerException != null)
{
exceptionObject = exceptionObject.InnerException;
}
switch (exceptionObject.GetType().ToString())
{
case "System.Threading.ThreadAbortException":
HttpContext.Current.Server.ClearError();
break;
default:
// log exception ...
//Custom method to log error
Elmah.ErrorSignal.FromCurrentContext().Raise(exceptionObject);
break;
}
}
}
catch
{
//Avoiding further exception from exception handling
}
}

C# saving an image from PictureBox

i have a code like this:
private void Load_Button_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog()==DialogResult.OK){
MessageBox.Show(dialog.FileName,"My Application", MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
string s;
s=".bmp";
if (dialog.FileName.Substring(dialog.FileName.LastIndexOf('.')).Equals(s))
{
picBox_1.Load(dialog.FileName);
BitmapFile = new Bitmap(dialog.FileName.ToString());
}
else {
MessageBox.Show("Not a BMP file!");
}
}
}
so, load image. and have an error in this:
private void Save_Button_Click(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog();
try
{
if (picBox_1.Image != null)
{
if (dialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(dialog.FileName, "My Application", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
string s;
s = ".bmp";
if (dialog.FileName.Substring(dialog.FileName.LastIndexOf('.')).Equals(s))
{
picBox_1.Image.Save(dialog.FileName.ToString());
//BitmapFile.Dispose();
}
else
{
MessageBox.Show("Not a BMP file!");
}
}
}
else
{
MessageBox.Show("My PicBox is empty!");
}
}
catch (Exception) { MessageBox.Show("Cannot save file, error!"); }
}
this is general GDI error. I suppose, that i can't write to file (not enough rights, maybe). how can i improve this error?
you should catch the exceptions properly, not with a MessageBox which tells you nothing about the exact exception thrown!
at minimum your catch block should look like this:
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
and I say at minimum because you should in fact log the exception somewhere, using a logging framework like NLog or Log4Net and dump stack trace and other details. You are not even able to tell the excact type of Exception if you show a message with a static string and not the details of the actual exception.
You should only catch specific exceptions that you intend to handle or recover from, and log the details. Never catch Exception as you would potentially be masking bigger issues with your server if they occur.
Unexpected exceptions should bubble up so that the cause can quickly be identified when they occur.
See here for Best Practices for Handling Exceptions.
You're eating the exception and losing all the juicy detail. Try changing your catch block to something like this to see what's going on:
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString(), "Error Saving Image", MessageBoxIcons.Error);
}
Also, consider implementing some logging (to the event viewer and/or text file. This will allow you to have a simple message box, but with all the juicy detail put somewhere useful to fetch after the event.
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error Saving Image", MessageBoxIcon.Error);
// _logger is a private field on this class in this case.
_logger.Log(ex, string.Format("Saving image to {0}", dialog.Filename))
}
You could look at Log4net amongst other things for the actual logging, but at the very least write a class to write exception detail to the event viewer.

Categories

Resources