Skip to content

Commit 82a1897

Browse files
committed
Provide preview of JSON when parse fails
Clean up formatting
1 parent a6b4103 commit 82a1897

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,6 +184,11 @@ 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();
188193
return TRITONJSON_STATUSSUCCESS;
189194
}
@@ -194,6 +199,31 @@ class TritonJson {
194199
return Parse(json.data(), json.size());
195200
}
196201

202+
// Helper function for Parse(const char* base, const size_t size) to handle
203+
// errors. Return error message if parsing failed.
204+
TRITONJSON_STATUSTYPE ParseErrorHandler(
205+
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)