Skip to content

Commit 60cdf40

Browse files
JH23XJonas Holzner
andauthored
server : handle exception on wrong type in request (#6452)
Co-authored-by: Jonas Holzner <[email protected]>
1 parent bb43cf7 commit 60cdf40

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

examples/server/utils.hpp

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,23 @@ extern bool server_log_json;
4949
#define LOG_WARNING(MSG, ...) server_log("WARN", __func__, __LINE__, MSG, __VA_ARGS__)
5050
#define LOG_INFO( MSG, ...) server_log("INFO", __func__, __LINE__, MSG, __VA_ARGS__)
5151

52+
static inline void server_log(const char *level, const char *function, int line, const char *message, const nlohmann::ordered_json &extra);
53+
5254
template <typename T>
5355
static T json_value(const json &body, const std::string &key, const T &default_value) {
5456
// Fallback null to default value
55-
return body.contains(key) && !body.at(key).is_null()
56-
? body.value(key, default_value)
57-
: default_value;
57+
if (body.contains(key) && !body.at(key).is_null()){
58+
try {
59+
return body.value(key, default_value);
60+
}
61+
catch (nlohmann::json_abi_v3_11_3::detail::type_error const&){
62+
std::string message = "Wrong type supplied for parameter '" + key + "'. Expected '" + typeid(default_value).name() + "', using default value.";
63+
server_log("WARN", __func__, __LINE__, message.c_str(), body);
64+
return default_value;
65+
}
66+
} else {
67+
return default_value;
68+
}
5869
}
5970

6071
static inline void server_log(const char *level, const char *function, int line, const char *message, const nlohmann::ordered_json &extra) {

0 commit comments

Comments
 (0)