我尝试在抛出 FormatException 时将用户重定向到错误页面,并检索在自定义异常类中生成的自定义消息。我需要使用在源(这里:产品)类中捕获的异常。我使用会话状态来存储异常并检索原始异常。
使用以下代码,我得到了我需要的东西,唯一的问题是我无法检索自定义异常消息,我只是得到:
输入字符串的格式不正确。
而我需要获取自定义消息(没有原始消息)。
我调查了各种来源和异常抛出方式,但没有遇到解决方案。
这就像我举的一个学术例子。这是我的自定义课程
类
public class Product
{
private int price;
public int Price {
get { return price; }
set
{
try
{
price = value;
}
catch (FormatException e)
{
throw new CustomException();
}
}
}
public Product(int price) {
this.Price = price;
}
}
public class CustomException : FormatException
{
public CustomException() : base() { }
public override string Message
{
get
{
return "Exception caught!";
}
}
}
代码隐藏
public partial class Input : System.Web.UI.Page{
protected void btn_Click(object sender, EventArgs e){
Product product = new Product(Convert.ToInt32(txt.Text));
}
}
public partial class ErrorPage : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
Exception err = Session["LastError"] as Exception;
if (err != null)
{
err = err.GetBaseException();
lblError.Text = err.Message;
}
}
}
全球.asax 文件
<%@ Application Codebehind="Global.asax.cs"
Inherits="ExceptionTest.Global" Language="C#" %>
<script runat="server">
void Application_Error(object sender, EventArgs e){
Exception err = Server.GetLastError();
Session.Add("LastError", err);}
void Session_Start(object sender, EventArgs e){
Session["LastError"] = "";}
</script>
谁能帮忙?
当您尝试转换为Int32
并且从未到达try-catch
块时,会引发异常。如果你想测试你的CustomException
,试试这个
protected void btn_Click(object sender, EventArgs e){
try {
Product product = new Product(Convert.ToInt32(txt.Text));
}
catch (FormatException e)
{
throw new CustomException();
}
}
更新:
如果你真的需要在Product
课上检查,你需要在那里转换你的文本。(但这是个坏主意。尽快转换为预期类型)
您的代码将如下所示:
public class Product
{
private int price;
public int Price {
get { return price; }
set
{
price = value;
}
}
public Product(string price) {
try
{
this.Price = Convert.ToInt32(price);
}
catch (FormatException e)
{
throw new CustomException();
}
}
}
您的"代码隐藏":
public partial class Input : System.Web.UI.Page{
protected void btn_Click(object sender, EventArgs e){
Product product = new Product(txt.Text);
}
}
使用 Html 编码清理错误消息。
public partial class ErrorPage : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
Exception err = Session["LastError"] as Exception;
if (err != null)
{
err = err.GetBaseException();
lblError.Text = Server.HtmlEncode(err.Message);
}
}
}