This project is read-only.

Exception Inside a MediaTypeFormatter

Topics: Web Api
May 27, 2011 at 4:32 AM

I've created my own JSON formatter and have made my life a little easier by catching errors inside the OnReadFromStream method:

public override object OnReadFromStream(Type type, Stream stream, HttpContentHeaders contentHeaders) {
    try {
        var serializer = JsonSerializer.Create(this.serializerSettings);
        var reader = GetReader(contentHeaders, stream);
        return serializer.Deserialize(reader, type);
    } catch {
        return null;

That way in my resource I can check for nulls and then determine how I want to proceed, like logging and returning a more helpful message.
Example: Status: 400 Bad Request with a message that says something like "Invalid Payload" (or whatever).

This works great when someone attempts to post malformed JSON, but when they are using a Content-Type of text/xml (and post bad XML) the built in MediaTypeFormatter throws an exception and they receive a status code 500 Internal Server Error.  This is kind of deceiving and makes it look like there was a problem on the server that couldn't be handled.  Is there any reason you don't return null values?  Am I heading down a slippery slope with this logic or should I write my own XML MediaTypeFormatter to do something similar?