Unified error responses for Nancy 1.x (RFC7807)
C#
Switch branches/tags
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.paket
Tests/Nancy.ProblemDetails.Tests
src/Nancy.ProblemDetails
.gitattributes
.gitignore
Nancy.ProblemDetails.sln
README.md
after.Nancy.ProblemDetails.sln.targets
appveyor.yml
paket.dependencies
paket.lock

README.md

Nancy.ProblemDetails Build status NuGet version codecov.io codefactor

About

Nancy responses following RFC7807 - Problem Details for HTTP APIs.

Currently supports JSON

Installation

package-install Nancy.ProblemDetails

Usage

Problem Details as model

In your modules you can simply return Tavis.ProblemDocument. For example

public class SomeModule : NancyModule
{
    public SomeModule()
    {
        Post["some"] = _ => ComePostSome();
    }

    private dynamic ComeGetSome()
    {
        var model = this.BindAndValidate<Some>();

        if (ModelValidationResult.IsValid == false)
        {
            return new Tavis.ProblemDocument
            {
                StatusCode = System.Net.HttpStatusCode.BadRequest
            };
        }

        // do somethign else
        return 200;
    }
}

Nancy Response type

You can also use ProblemJsonResponse (for example in Pipelines).

public class SomeHandlerStartup : IRequestStartup
{
    public void Initialize(IPipelines pipelines, NancyContext context)
    {
        pipelines.AfterRequest.AddItemToEndOfPipeline(ReturnProblemDetails);
    }

    private static void ReturnProblemDetails(NancyContext ctx)
    {
        ctx.Response = new ProblemJsonResponse(new ProblemDocument
        {
            StatusCode = System.Net.HttpStatusCode.Forbidden
        });
    }
}

Status code handler

Finally, you can handle selected errors globally by implementing the abstract ProblemJsonStatusCodeHandler class

public class ServerErrorHandler : ProblemJsonStatusCodeHandler
{
    public ServerErrorHandler()
    {
        // wire up handlers using the When method
        When(CodeIsForbidden, HandleForbidden);
    }

    private static bool CodeIsForbidden(HttpStatusCode code, NancyContext context)
    {
        // return true if codeshould be handled
        return code == HttpStatusCode.Forbidden;
    }

    private static ProblemDocument HandleForbidden(NancyContext context)
    {
        // create the details document to be serialized
        return new ProblemDocument
        {
            ProblemType = new Uri("http://my.api/error-codes/unauthorized")
        };
    }