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

NancyFX - Return custom error response on uncaught exception

我正在尝试使用 Nancy 让我的自托管服务在出现未捕获的异常时 return 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();

运气不好。

啊,这是一个 CORS 问题。

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

    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);
    }

但是当响应在我的状态代码处理程序中被替换时,我需要再次设置这些headers:

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");
    }
}