我有一个 Web 项目,它有一个名为 editemployee.aspx 的页面。背后的代码是 editemployee.aspx.cs。从该代码中,我将另一个项目称为类库。我在该类库中调用的方法看起来像...
public static Employee GetItem(int employeeid)
{
try
{
Employee chosenemployee = EmployeeDB.GetItem(employeeid);
chosenemployee.EmployeeInsuranceRecord = EmployeeInsuranceRecordManager.GetItem(employeeid);
return chosenemployee;
}
catch (Exception ex)
{
if (ex is NullReferenceException)
{
//How can I return gracefully from here
//without disrupting the user experience?
}
else
{
throw ex; //if it makes it this far, it must be some other unknown error and I need an exception to be thrown for real so I can track down the bug.
}
}
}
基本上,此代码根据传递的 EmployeeID 从数据访问层获取完整的员工记录。如果异常是 NullReferenceException,则意味着以某种方式通过了伪造的 EmployeeID。在那种情况下,我想要发生的是返回到调用 .aspx.cs 页面,停止在那里整理 Employee 的过程,并显示一个 JavaScript 警告框,上面写着“提供的 EmployeeID 无效”。
所以我试着说:
if (ex is NullReferenceException)
{
Response.Write("<script>alert('"The EmployeeID supplied is not valid."')</script>");
}
但这在单独的类库中不起作用,它不识别 Response.Write。
基本上,我只需要一种方法来发出信号,从这个方法中,调用页面只是停止并优雅地显示错误,而不是给用户一个巨大的丑陋的不可恢复的错误消息。有什么建议吗?
最佳答案
为什么不从 editemployee.aspx.cs 中捕获 NullReferenceException
?
像这样的东西:
try
{
var employee = Employee.GetItem(int employeeid)
}
catch(NullReferenceException ex)
{
Response.Write("<script>alert('"The EmployeeID supplied is not valid."')</script>");
}
此外,您应该不使用is
运算符来过滤异常类型,而是在 catch 语句中添加正确的类型。
A catch block can specify an exception type to catch. This type is called an exception filter, and must either be the Exception type, or derived from this type. Application-defined exceptions should derive from ApplicationException.
( source )
最后,推荐的做法是抛出更多指定的Exception
。在您的情况下,自定义 EmployeeNotFoundException
最好从您的业务层抛出。
catch(NullReferenceException ex)
{
throw new EmployeeNotFoundException(ex);
}
关于c# - 从另一个类的捕获中优雅地返回到 .aspx.cs 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8485793/