NancyFX - 返回未捕获异常的自定义错误响应

时间:2015-02-12 21:18:36

标签: c# .net nancy

我试图使用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;
    }

虽然我已验证OnErrorHandle中的代码已执行(请参阅评论),但我的客户仍会收到404.我还尝试使用

        var exception = context.Items[NancyEngine.ERROR_EXCEPTION] as Exception;

而不是

        var exception = context.GetException();

没有运气。

1 个答案:

答案 0 :(得分:6)

Gah,所以这是一个CORS问题。

我自动将CORS标头添加到响应中:

    protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
    {
        pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
        {
            ctx.Response.WithHeader("Access-Control-Allow-Origin", "*")
                .WithHeader("Access-Control-Allow-Methods", "POST,GET")
                .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type");
        });

        pipelines.OnError.AddItemToEndOfPipeline((ctx, exc) =>
        {
            if (exc != null)
            {
                throw exc;
            }

            return HttpStatusCode.InternalServerError;
        });

        base.RequestStartup(container, pipelines, context);
    }

但是当我的状态码处理程序中的替换时,我需要再次设置这些标题:

public class JsonErrorStatusCodeHandler : IStatusCodeHandler
{
    public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
    {
        if (statusCode != HttpStatusCode.InternalServerError)
        {
            return false;
        }

        var exception = context.GetException();

        return exception != null;
    }


    public void Handle(HttpStatusCode statusCode, NancyContext context)
    {
        var exception = context.GetException();

        JsonResponse response = new JsonResponse(string.Format("{0}:{1}", exception, exception.Message), new DefaultJsonSerializer());

        response.StatusCode = HttpStatusCode.InternalServerError;

        context.Response = response;

        context.Response.WithHeader("Access-Control-Allow-Origin", "*")
            .WithHeader("Access-Control-Allow-Methods", "POST,GET")
            .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type");
    }
}