Answer:
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" Trace="true" %>
<!DOCTYPE html>
<html>
<head>
<title>IndexOutOfRange Exception Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Click the button to generate an exception</h2>
<asp:Button ID="btnGenerateException" runat="server" Text="Generate Exception" OnClick="btnGenerateException_Click" />
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnGenerateException_Click(object sender, EventArgs e)
{
try
{
// Intentionally causing an IndexOutOfRangeException
int[] numbers = { 1, 2, 3 };
int value = numbers[5]; // This will throw IndexOutOfRangeException
}
catch (Exception ex)
{
// Log the exception to the trace
Trace.Warn("Exception caught", ex.Message);
// Redirect the user to a custom error page
Response.Redirect("~/ErrorPage.aspx");
}
}
}
}
Web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="~/ErrorPage.aspx">
<error statusCode="500" redirect="~/ErrorPage.aspx"/>
</customErrors>
<trace enabled="true" pageOutput="true" />
</system.web>
<system.webServer>
<httpErrors errorMode="Custom">
<error statusCode="500" path="/ErrorPage.aspx" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
</configuration>
ErrorPage.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ErrorPage.aspx.cs" Inherits="WebApplication1.ErrorPage" %>
<!DOCTYPE html>
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h2>Oops! Something went wrong.</h2>
<p>Sorry, there was an error while processing your request. Please try again later.</p>
</body>
</html>