我有一个使用ServiceStack和ServiceStack.Razor构建的应用程序。我无法按照我想要的方式配置错误处理。这是目标:
首先,我尝试使用CustomHttpHandlers来解决401,403和404错误。这一直有效,直到我设置GlobalHtmlErrorHttpHandler来捕获其他错误。我发现GlobalHtmlErrorHttpHandler总是先命中,所有错误都被重定向到全局错误页面。
然后我删除了GlobalHtmlErrorHttpHandler并使用了AppHost.ServiceExceptionHandler,只要从服务内部抛出违规异常,它就可以正常工作。如果在服务外部发生错误,我们仍会收到ServiceStack错误消息。此外,我还必须添加一个“转义子句”,以便将401,403和404错误传递给相应的CustomHttpHandler。
然后我设置AppHost.ExceptionHandler来捕获其他所有内容。这是我的AppHost的一个片段。我觉得我必须错过一些方法来处理这个更简单的方法。有任何想法吗?谢谢!
public override void Configure(Funq.Container container)
{
SetConfig(new EndpointHostConfig
{
DebugMode = false,
AllowFileExtensions = { "swf", "webm", "mp4" },
CustomHttpHandlers =
{
{ HttpStatusCode.Unauthorized, new RazorHandler("/AccessDenied") },
{ HttpStatusCode.Forbidden, new RazorHandler("/AccessDenied") },
{ HttpStatusCode.NotFound, new RazorHandler("/NotFound") }
}
});
// For exceptions occurring within service methods:
this.ServiceExceptionHandler = (req, exc) =>
{
// Allow the error to fall through to the appropriate custom http handler;
// This feels like a kluge.
if (exc is HttpError)
{
IServiceStackHttpHandler handler = null;
if (this.Config.CustomHttpHandlers.TryGetValue(((HttpError)exc).StatusCode, out handler))
{
return new HttpResult() { View = ((RazorHandler)handler).PathInfo.Substring(1) };
}
}
Log.ErrorException(String.Format("Error handling {0}: {1}", req.GetType().FullName, JsonSerializer.SerializeToString(req)), exc);
return new HttpResult() { View = "Error" };
};
// For exceptions outside of service methods:
this.ExceptionHandler = (req, res, op, exc) =>
{
Log.ErrorException(String.Format("Error handling request {0} {1}", op, req.AbsoluteUri), exc);
res.Redirect("~/Error".ToAbsoluteUrl());
};