【问题标题】:NancyFX - Return custom error response on uncaught exceptionNancyFX - 返回未捕获异常的自定义错误响应
【发布时间】: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;
    }

虽然我已经验证了OnErrorHandle 中的代码已执行(参见 cmets),但我的客户仍然收到 404。我也尝试过使用

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

而不是

        var exception = context.GetException();

没有运气。

【问题讨论】:

    标签: c# .net nancy


    【解决方案1】:

    啊,所以这是一个 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");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2019-08-03
      • 2020-09-30
      • 2021-11-13
      • 2015-07-05
      相关资源
      最近更新 更多