【发布时间】:2015-02-12 21:18:35
【问题描述】:
我正在尝试使用 Nancy 让我的自托管服务在未捕获的异常时返回 json 格式的错误。但是,我总是收到回复:
{"readyState":4,"status":404,"statusText":"error"}
(以下是网络上几个例子的合并)。
我的引导程序包含以下内容:
pipelines.OnError.AddItemToEndOfPipeline((ctx, exc) =>
{
if (exc is Exception)
{
// this is always executed upon failure to handle an exception.
Log.Error("Unhandled error on request: " + context.Request.Url + " : " + exc.Message, exc);
JsonResponse response = new JsonResponse(string.Format("{0}:{1}", exc, exc.Message), new DefaultJsonSerializer());
response.StatusCode = HttpStatusCode.InternalServerError;
return response;
}
return HttpStatusCode.InternalServerError;
});
我有一个 StatusCodeHandler:
public class JsonErrorStatusCodeHandler : IStatusCodeHandler
{
public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
{
return statusCode == HttpStatusCode.InternalServerError;
}
public void Handle(HttpStatusCode statusCode, NancyContext context)
{
var exception = context.GetException();
if (exception != null)
{
// never executed
}
// this is executed
JsonResponse response = new JsonResponse("wtf"), new DefaultJsonSerializer());
response.StatusCode = HttpStatusCode.InternalServerError;
context.Response = response;
}
虽然我已经验证了OnError 和Handle 中的代码已执行(参见 cmets),但我的客户仍然收到 404。我也尝试过使用
var exception = context.Items[NancyEngine.ERROR_EXCEPTION] as Exception;
而不是
var exception = context.GetException();
没有运气。
【问题讨论】: