Created
November 13, 2013 00:31
-
-
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??
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()"