Skip to content

Commit 35b1acf

Browse files
committed
Provide preview of JSON when parse fails
1 parent a6b4103 commit 35b1acf

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

include/triton/common/triton_json.h

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,13 @@ class TritonJson {
184184
std::string(GetParseError_En(document_.GetParseError())) + " at " +
185185
std::to_string(document_.GetErrorOffset())));
186186
}
187+
TRITONJSON_STATUSTYPE status = ParseErrorHandler(document_, std::string(base, size));
188+
if (status != TRITONJSON_STATUSSUCCESS) {
189+
return status;
190+
}
191+
187192
allocator_ = &document_.GetAllocator();
193+
188194
return TRITONJSON_STATUSSUCCESS;
189195
}
190196

@@ -194,6 +200,30 @@ class TritonJson {
194200
return Parse(json.data(), json.size());
195201
}
196202

203+
// Help Parse(const char* base, const size_t size) handle errors.
204+
// Return error message if parsing failed.
205+
TRITONJSON_STATUSTYPE ParseErrorHandler(const rapidjson::Document& document, const std::string& json)
206+
{
207+
if (document.HasParseError()) {
208+
std::ostringstream error_stream;
209+
error_stream << "failed to parse the request JSON buffer: "
210+
<< GetParseError_En(document.GetParseError())
211+
<< " at offset " << document.GetErrorOffset() << ".";
212+
213+
// Show part of the JSON to help debugging
214+
const size_t preview_length = 100;
215+
std::string json_preview = json.substr(0, preview_length);
216+
if (json.size() > preview_length) {
217+
json_preview += "...";
218+
}
219+
220+
error_stream << " JSON Preview: \"" << json_preview << "\"";
221+
222+
return TRITONJSON_STATUSRETURN(error_stream.str());
223+
}
224+
return TRITONJSON_STATUSSUCCESS;
225+
}
226+
197227
// Write JSON representation into a 'buffer' in a compact
198228
// format. Can only be called for a top-level document value,
199229
// otherwise error is returned.

0 commit comments

Comments
 (0)