gpt4 book ai didi

c# - 如何处理 ASP.NET MVC 中的 "default"异常?

转载 作者:行者123 更新时间:2023-12-03 09:03:15 25 4
gpt4 key购买 nike

想象一下这个场景:

public ActionResult MyAction(int myParam)
{
if(ModelState.IsValid)
{
// do something useful
return RedirectToAction("NextAction");
}

return RedirectToAction("Error", "Error");
}

这最终出现在蓝屏死机上,而不是我的错误 Controller 上。我当然可以掩盖这一点,但我想在这里回归。所以,我尝试了这个:
public ActionResult MyAction(int myParam)
{
try
{
if(ModelState.IsValid)
{
// do something useful
return RedirectToAction("NextAction");
}
}
catch(Exception ex)
{
return RedirectToAction("Error", "Error");
}
}

但这不会编译,说明并非所有路径都返回一个值,即使通过该代码的任何路径都应该以 ActionResult 结束。如果将返回值放在 finally 中,则相同。命令,提示“控制不能离开 finally 子句的主体”。

有没有更好的方法来处理这个问题,或者我是否必须在这个 Controller 操作的底部留下一个悬空的默认返回?

最佳答案

你不能编译那个,因为你忘记了这部分

public ActionResult MyAction(int myParam)
{
try
{
if(ModelState.IsValid)
{
// do something useful
return RedirectToAction("NextAction");
}
else{
return RedirectToAction("Error", "Error");
}
}
catch(Exception ex)
{
return RedirectToAction("Error", "Error");
}
}

如果这是模型状态无效,则没有返回 View 。

关于c# - 如何处理 ASP.NET MVC 中的 "default"异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43044382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com