REST API中的异常适当的http响应

时间:2014-04-28 22:03:36

标签: rest exception-handling nancy

在我的模块中,我希望能够在“坏事发生”时抛出异常并让框架自动捕获并将这些异常转换为适当的http响应(包括状态代码和有效负载,如果适用)。我知道我可以在管道上的OnError函数中从我的引导程序执行此操作。但有没有更好或更成熟的方法呢?

这就是我现在所拥有的:

pipelines.OnError += (ctx, err) => HandleExceptions(err, ctx);

方法:

static Response HandleExceptions(Exception err, NancyContext ctx)
{
    if (err is NoAvailableHandlerException)
    {
        return ctx.Response
            .WithStringContents("No handler exists to for the given command")
            .WithStatusCode(HttpStatusCode.NotImplemented);
    }

    if (err is UserAlreadyExistsException)
    {
        return ctx.Response
            .WithStringContents(err.Message)
            .WithStatusCode(HttpStatusCode.BadRequest);
    }

    if (err is NotImplementedException)
    {
        return ctx.Response
            .WithStringContents(err.Message)
            .WithStatusCode(HttpStatusCode.NotImplemented);
    }

    if (err is UnauthorizedAccessException)
    {
        return ctx.Response
            .WithStatusCode(HttpStatusCode.Unauthorized);
    }

    if (err is TokenDoesNotExistException)
    {
        return ctx.Response
            .WithStringContents("The token you tried to use is not valid.")
            .WithStatusCode(HttpStatusCode.Unauthorized);
    }

    if (err is TokenExpiredException)
    {
        return ctx.Response
            .WithStringContents(
                "The token you tried to use has expired. Please log in to get a new one.")
            .WithStatusCode(HttpStatusCode.Unauthorized);
    }

    string exceptionText = AddException(err);
    return new Response()
        .WithStringContents(
            string.Format("The {0} request to '{1}' resulted in an unhandled exception!\r\n\r\n{2}",
                            ctx.Request.Method, ctx.Request.Url, exceptionText))
        .WithStatusCode(HttpStatusCode.InternalServerError);
}

就像我说的,这很有效。但似乎有点普遍,我可能正在重新发明轮子,而且还没有找到合适的博客网站让我直截了当。

0 个答案:

没有答案