我在问题中看到了类似的帖子Error Handling with WCF Service and Client Application,但我需要更多的帮助。
我有一个带有WCF服务的MVC项目。我知道WCF需要抛出FaultException。但我的问题是,在WCF中显示由错误创建的错误消息的最佳方法是什么。我只想将所有错误(可能是所有FaultException)重定向到一个错误页面(将是通用的),但消息将是不同的。
我还想使用[HandleError]属性,这样我就不必为调用WCF服务的所有方法实现捕获FaultException。
答案 0 :(得分:0)
如您所知,如何处理WCF异常,但在我看来,观察这些更好:
1 - 这不好向用户展示异常消息,这样可以更好地显示非常容易理解的消息,例如“操作失败可能会出现后端服务问题,请重试或通知管理员”
2-重定向到公共错误页面是无聊的最终用户。
3-这样可以更好地向用户显示公共提示,告知用户操作失败的确切位置是用户执行操作而不是将其重定向到其他页面。
4-最后如果你想做你想做的事,试试这些:
try
{
//Call your wcf
}
catch(Exception exp)
{
//Logging.Log(LoggingMode.Error, "You message , EXP:{0}...", exp.ToString());
Response.Redirect("~/ErrorPages/Oops.aspx?Error=WCfOperationFailed", false);
}
错误页面中的page_load:
switch (Request.QueryString["Error"].ToString())
{
case "WCfOperationFailed":
litError.Text = string.Format("<h2>Error!.</h2><br/><p>{0}.</p>",GetError());
break;
default:
break;
}
public string GetError()
{
Exception lastError = Server.GetLastError();
return lastError.ToString();
}
或者您可以将错误消息重定向为QueryString
到错误页面,并在Page_load
中向用户显示,如:
//in catch block
Response.Redirect("~/ErrorPages/Oops.aspx?Error="+exp.Message, false);
错误页面Page_load
:
txtError.Text = Request.QueryString["Error"].ToString();
但是,您可以通过向Global.asax文件中的Application_Error处理程序添加代码来捕获应用程序中任何位置发生的错误:
void Application_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError();
if (exc is HttpUnhandledException)
{
// Pass the error on to the error page.
Server.Transfer("ErrorPage.aspx?Error="+exc.Message, true);
}
}
此链接可以提供一些示例 Error Handling