Those two code snippets are very similar.. I think we should go more generic here, maybe you can add a static `XContentHelper.toString(ToXContent foo)` which acts like in the `SearchSourceBuilder` and does not throw an exception, but returns an error JSON

```java

    @Override
    public String toString() {
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint();
            toXContent(builder, ToXContent.EMPTY_PARAMS);
            return builder.string();
        } catch (Exception e) {
            return "{ \"error\" : \"" + e.getMessage() + "\"}";
        }
    }
```

There should be another `XContentHelper.toString(ToXContent foo, boolean wrapInObject)` method which adds the needed `builder.startObject()` and `builder.endObject` calls, if specified. 

With this change, both of this calls, would basically be one-liners.

Hope it makes sense...