Exemple #1
0
        public void Handle(HttpStatusCode statusCode, NancyContext context)
        {
            var clientWantsHtml = ShouldRenderFriendlyErrorPage(context);

            switch (statusCode)
            {
            case HttpStatusCode.NotFound:
                if (clientWantsHtml)
                {
                    context.Response = RenderView(context, "Shared/NotFound")
                                       .WithStatusCode(HttpStatusCode.NotFound)
                                       .WithHeader("Reason", "The resource you were looking for was not found.");
                }
                else
                {
                    context.Response =
                        JsonErrorResponse.FromMessage("The resource you requested was not found.", _serializer,
                                                      HttpStatusCode.NotFound);
                }
                break;

            case HttpStatusCode.InternalServerError:
                var exception = GetExceptionFromContext(context);

                Log.Error(exception, "Error {Method} to {Url} in {ModuleName} to {ModulePath} as {User}",
                          context.Request.Method, context.Request.Url,
                          context.NegotiationContext == null ? "Unknown ModuleName" : context.NegotiationContext.ModuleName,
                          context.NegotiationContext == null ? "Unknown ModulePath" : context.NegotiationContext.ModulePath,
                          context.CurrentUser == null ? "Anonymous User" : context.CurrentUser.UserName);

                if (clientWantsHtml)
                {
                    context.Response = RenderView(context, "Shared/Error", new { ErrorMessage = exception.Message, FullException = AppEnvironment.IsProduction() ? string.Empty : exception.ToString() })
                                       .WithStatusCode(HttpStatusCode.InternalServerError)
                                       .WithHeader("Reason", exception.Message);
                }
                else
                {
                    context.Response = JsonErrorResponse.FromException(exception, _serializer);
                }
                break;
            }
        }
Exemple #2
0
 public static Response AsError(this IResponseFormatter formatter, string message, HttpStatusCode statusCode = HttpStatusCode.InternalServerError)
 {
     return(JsonErrorResponse.FromMessage(message, formatter.Serializers.FirstOrDefault(s => s.CanSerialize("application/json")), statusCode));
 }