ASP.NET where does throw new exception error get displayed - asp.net

Code snippet..
if (regionalApprover == null)
{
throw new Exception(string.Format("The regional approver for {0} could not be found", companyData["Country"]));
}
How does the user actually see this error ?

The result of an unhandled exception depends on a variety of factors, including
where the web request is coming from,
the settings of the <customErrors> Element in your web.config and
the contents of Application_Error in your global.asax codebehind file.
In the default configuration, IIS will log the error into the Windows event log. In addition, it is shown in the browser by ASP.NET if the web request comes from localhost.

If you're trying to display an error message on the page (that the user is supposed to see), don't use Exceptions.
It's a much better idea to add an errors section to the page that you can add the messages to before showing the page to the user.

Related

Redirected to Default.aspx instead of set error 500 page on exception

In the site settings of our DotNetNuke installation, we set the Default Page for "500 Error Page" as you can see below.
After setting this, we were expecting to be redirected when an error occurs. Instead we're still redirected the the "Default.aspx?tabid=..." page.
Why isn't the correct page shown?
What do we need to change for it to work?
(We're using v9.02.00 366, .NET Framework 4.6)
EDIT: Here's how I force the error to occur using a custom module.
public partial class TriggerError500 : PortalModuleBase
{
protected void Page_Load(object sender, EventArgs e)
{
if(UserId == -1)
{
throw new NotImplementedException();
}
}
}
This module has been placed on a public page to test the error 500 page.
The 500 error page will most likely only be used when an exception is completely unhandled. For example, if an exception is handled by a developer, then a friendly message will be shown on the page with part of the exception in the URL. This may account for the URL thing you're seeing. It's the same page as the module in question, but in a different format.
When the exception is not handled, a visitor would ordinarily be shown the infamous "yellow screen of death" (YSOD) with error details. Depending on the settings in the web.config, the level of detail will be generic or detailed. I believe that this is the use case intended for the 500 error page. This is when you should see it.
If my memory serves me right, you may want to try this in your web.config:
<customErrors mode="On" defaultRedirect="500" />
A setting that will affect error handling at a platform level can be toggled in the security section
Screen Shot here
Due to the way that DNN handles the loading of modules, and pages, the code that you are writing does not actually trigger an HTTP 500 error, as the page itself is loaded properly. The module loading error is captured by the framework and the error is logged to the Admin Logs, but the page itself is rendered.
You typically get an HTTP 500 error when you cannot connect to the database or otherwise, in those cases the DNN will adhere to the rules.
It is possible, that you could set Response.StatusCode = 500; and then end the response and get the desired behavior, but i have NOT tested this.

Error Handling ASP.NET WebApi

I have a global error handling for the controller which is working fine. But sometimes when any web.config element are missing or can't able to load it shows the error screen and hitting the application-error in the global.asax as the the exception never reaches the pipe line. Also I was able to redirect to a custom error page by setting custom error as remoteonly with redirection page but not able to log it as not hitting application-error in global.asax. Does anyone know how to handle the exception here
I guess, Exception handles your code only, the exception which you were taking is before any code to be execute and it will handle by Web Server i.e. IIS

Passing Exception Information from Global.asax to ErrorPage.aspx

I have a global error handler in Global.asax and am trying to display the exception information in a page called ErrorPage.aspx. I've read Microsoft's page about passing information between asp.net pages (http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx). I don't think any of these will work:
QueryString: I'm concerned that the length of the exception will
exceed the maximum length of the QueryString.
Post Information: The Global.asax page doesn't have any form fields.
Session State: Session state is not available in Global.asax
Public Values: I think this only works with .aspx pages
Control from Source Page: Global.asax can't have asp.net controls.
My current thought is that it would be logical to create an instance of the ErrorPage object and navigate to it (as you could do in a Windows Forms application), but I don't know how to do that or if it is possible in asp.net.
Ultimately, I'm looking for a way to display errors caught by a global error handler in a standard .aspx page. Any suggestions would be helpful.
What I would do:
Log exception information including stack trace in a log file,
Redirect to an ErrorPage with error code (regular http errorcodes + a generic 'unknown error' one + maybe some custom errors that make sense for the application) passed in query string parameter,
Display a predefined message for this error code.
There is little reason to display actual error messages to end users, more detailed error information not withstanding. If you want to display full information for debugging purposes, turn custom errors off in web.config

Redirecting user to dynamic error page

Can I configure ASP.NET custom errors so that it would redirect to other site when error has occurred. Even more, I would like to redirect to different web page every time.
Here is my simplified actual case:
User opens my pages with query ?urlpage=http://test.com/error.html and I would like to redirect to this page when error occurs.
How should I act in this scenario?
See http://msdn.microsoft.com/en-us/library/ed577840.aspx
And in the Page_Error method, just do:
var redirectUrl = Request.QueryString["urlpage"];
if (redirectUrl != null)
Response.Redirect(redirectUrl);
There are a number of different resources in ASP.NET that will allow you to handle errors.
I found this article on the web.config file very informative : http://articles.sitepoint.com/article/web-config-file-demystified
In addition you can setup error handling inside of the global.asax file that will trap application wide errors and allow you to send emails, log information, etc.
You can also setup page specific error handling for more custom error information - but I find that a good general purpose error handling in global.asax works for most situations.
Finally, you can go into the properties for IIS and modify where errors are redirected. For instance, set the 500 error to point to a specific file (/error.aspx or similar).

Exception handling in ASP.NET Webforms

What is the preferred method for handling exceptions in ASP.NET Webforms?
You have the Page_Error method that you add (I think) at web.config level, and the entire site gets redirected there when an error occurs.
Does that mean you shouldn't use try-catch anywhere in a webforms application? (Assuming you don't want to hide any errors)
Only catch the errors you can handle. If you can handle them in a manner that allows the page to continue loading then do so. Any other exception that would wreck the page should not be handled in any control or page as you would not be able to do anything anyways. Let it go to the global.asax handler and make sure you log the exception.
In addition to Andrew's suggestion, make sure to update the web.config file to set CustomErrors to "On" and specify a generic error page to redirect these top level errors. Global_asax will still log the error, and then the user can see a friendly page. It will also allow you to configure a few of the standard type errors, such as 404s and 200s, plus much more.
Web Application will normally consists of UI, Business and Data access layer.Each layer must do its part regarding exception handling. Each layer must (for code re usability) check for error condition and wrap exception(after logging it) and maybe propagated to the calling layer. The UI layer should hide exception and display a friendly message. Catching all exception in UI maybe not a good idea. Exceptions if possible should be logged in Database. This will allow ease of maintainence and correction of bugs
Avoid catching exceptions as far as possible. Try and validate all inputs before you use them. Rigorously validation( both client and server side) inputs with help of validation controls, custom controls and regular expression is a must.
string fname = "abc";
//Always check for condition, like file exists etc...
if (System.IO.File.Exists(fname))
{
}
else
{
}
Always make sure clean up code is called. Using statement or try finally.
You can catch all exceptions in Global.asax (asp.net application file)
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error event\n" +
"Error in: " + Request.Url.ToString() +
"\nError Message:" + objErr.Message.ToString()+
"\nStack Trace:" + objErr.StackTrace.ToString();
EventLog.WriteEntry("Sample_WebApp",err,EventLogEntryType.Error);
Server.ClearError();
//additional actions...
}
and add <customerror> section in your web config to redirect user to a separate page
<customErrors defaultRedirect="error.htm" mode="On">
</customErrors>
Useful links
MSDN
MSDN
Exception Logging- Peter Bromberg
You should use try/catch in places where you can do something meaningful with error, like fixing it or taking a different approach.
For all other cases you should use global try/catch using web.config custom errors page or Application_Error event to log the error and possibly to show it to the user.
If you use validation controls or check and validate user input in your code behind that will go a long way to preventing errors. I do recommend having a generic error page that can log the error for you. In cases where you are unsure of what will happen i suggest catching the error and handling it if at all possible and work on finding a way to know that what you are going to run will work before doing it.
Do you have a specific example in mind of where you might expect to encounter an error of this sort. One that I know of is when a session expires and you can no longer process the page. I check for this on every page load before anything else is run and then redirect the user if this has occurred.

Resources