Skip to content

Instantly share code, notes, and snippets.

@gregberns
Created November 13, 2013 00:31
Show Gist options
  • Save gregberns/7441424 to your computer and use it in GitHub Desktop.
Save gregberns/7441424 to your computer and use it in GitHub Desktop.
NancyFX Error handling. The OnError, does not return anything in the message body. What am I doing wrong??
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
{
pipelines.OnError += (ctx, ex) =>
{
return ErrorResponse.FromException(ex);
};
base.RequestStartup(requestContainer, pipelines, context);
}
}
public class ErrorResponse : JsonResponse
{
readonly Error error;
private ErrorResponse(Error error) : base(error, new CustomJsonSerializer())
{
this.error = error;
}
public string ErrorMessage { get { return error.ErrorMessage; } }
public string FullException { get { return error.FullException; } }
public string[] Errors { get { return error.Errors; } }
public static ErrorResponse FromException(Exception ex)
{
var statusCode = HttpStatusCode.InternalServerError;
var error = new Error { ErrorMessage = ex.Message, FullException = ex.ToString() };
var response = new ErrorResponse(error);
response.StatusCode = statusCode;
return response;
}
class Error
{
public string ErrorMessage { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string FullException { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string[] Errors { get; set; }
}
}
public class CustomJsonSerializer : ISerializer
{
public CustomJsonSerializer()
{
//this.ContractResolver = new CamelCasePropertyNamesContractResolver();
//this.Formatting = Formatting.Indented;
}
public bool CanSerialize(string contentType)
{
//if (contentType == "application/json")
// return false;
//if (contentType == "text/json")
// return false;
//if (contentType == "text/html")
// return true;
//return false;
return true;
}
public IEnumerable<string> Extensions
{
get { throw new NotImplementedException(); }
}
public void Serialize<TModel>(string contentType, TModel model, Stream outputStream)
{
}
}
@gregberns
Copy link
Author

The issue was the the "CustomJsonSerializer.Serialize()" was not configured. So I'm dumb.
To resolve, instead of "private ErrorResponse(Error error) : base(error, new CustomJsonSerializer())", I just changed it to "DefaultJsonSerializer()"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment