Question

When an unhandled exception is thrown in WebAPI, this normally gets logged by ELMAH (in my installation) and a sensible response is returned to the jqXHR object that I can read.

But I had (a now resolved) issue with parsing some badly structured JSON that resulted in a StackOverflowException, in the Deserialize method (code below, just for context).

My issue is that this did not get treated as an unhandled exception, and instead (IIS I think) returned a 500 response, with an HTML page "Internal Server Error" with the message "The service is temporarily unavailable".

This therefore meant my JavaScript error handler crashed, as it was expecting JSON, not HTML in the response.

Is a StackOverflowException a special case that cannot, by its nature, be treated as an unhandled exception as any other, or are there other situations where ELMAH doesn't log the exception and that will also result in an HTML message being returned when JSON is expected?

Or does this mean that in WebAPI you have to put a try/catch round all code and to prevent unhandled exceptions ever occuring?

        private Models.Stream DeserializeStream(FileInfo dataFileInfo)
    {
        Models.Stream stream;

        using (var streamReader = new StreamReader(dataFileInfo.FullName))
        {
            using (var reader = new JsonTextReader(streamReader))
            {
                stream = Serializer.Deserialize<Models.Stream>(reader);
            }
        }

        return stream;
    }

Just for the avoidance of doubt I'm not looking for a solution to why the exception occured (I have that) just how best to handle these type of exceptions).

Était-ce utile?

La solution

Yes, StackOverflowException is one of a handle of special case exceptions which cannot be handled in the normal way.

There is some information here about how to handle it a bit.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top