Nancy responses following RFC7807 - Problem Details for HTTP APIs.
Currently supports JSON
package-install Nancy.ProblemDetails
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;
}
}
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
});
}
}
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")
};
}