With an implementation of IStreamWriter and IHasOptions that returns an image/jpeg result, if an error occurs in WriteTo, the global error handler in AppHost is not called, and the image/jpeg header stays, which results in a HTML error (generated by ServiceStack) with an image/jpeg HTTP Header.
Here's an example of how to reproduce this:
public class SampleStreamWriter : IStreamWriter, IHasOptions
{
void WriteTo(Stream responseStream)
{
// This would actually be a delegate
throw new ApplicationException("...");
}
public IDictionary<string, string> Options
{
get
{
return new Dictionary<string, string>
{
{HttpHeaders.ContentType, "image/jpeg"}
};
}
}
}
Since Options is called before WriteTo, it is not possible to try/catch inside WriteTo and change the Content-Type to e.g. "application/json", and manually override the error response.
How can this be implemented, so that the HTTP Response has the error's Content-Type value, and as a bonus, that the AppHost's ServiceExceptionHandler gets called for logging?
The CompressedFileResult class might be a good example to look at as it inherits IStreamWriter and IHasOptions. There are a few other classes used in testing that inherit from IStreamWriter as well (StreamWriterResult, ImageResult). Not sure those are as useful.
It seems like the simple answer is to do everything (Validation, get Image, build byte[]
, etc) before the 'WriteTo' method is called. If your Try/Catch
is within your Service you can push the exception up and use the Exception handling already provided. Obviously, this doesn't help when WriteTo
throws an exception but at this point in the Pipeline it seems like you've passed the point of Response manipulation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With