Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling with ServiceStack's IStreamWriter & IHasOptions

Tags:

servicestack

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?

like image 425
Christian Rondeau Avatar asked Nov 02 '22 22:11

Christian Rondeau


1 Answers

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.

like image 121
paaschpa Avatar answered Dec 06 '22 06:12

paaschpa