userver: /data/code/userver/libraries/protobuf/src/protobuf/json/exceptions.cpp Source File
Loading...
Searching...
No Matches
exceptions.cpp
1#include <userver/protobuf/json/exceptions.hpp>
2
3#include <type_traits>
4
5#include <fmt/format.h>
6
7USERVER_NAMESPACE_BEGIN
8
9namespace protobuf::json {
10
11namespace {
12
13template <typename TErrorCode>
14[[nodiscard]] constexpr const char* GetConversionErrorCodeStr(const TErrorCode code) noexcept {
15 if constexpr (std::is_same_v<TErrorCode, ParseErrorCode>) {
16 switch (code) {
17 case TErrorCode::kUnknownField:
18 return "unknown field";
19 case TErrorCode::kUnknownEnum:
20 return "unknown enum";
21 case TErrorCode::kMultipleOneofFields:
22 return "multiple oneof fields";
23 case TErrorCode::kInvalidType:
24 return "invalid type";
25 case TErrorCode::kInvalidValue:
26 return "invalid value";
27 default:
28 return "unexpected";
29 }
30 } else {
31 if (code == TErrorCode::kInvalidValue) {
32 return "invalid value";
33 } else {
34 return "unexpected";
35 }
36 }
37}
38
39template <typename TErrorCode>
40[[nodiscard]] constexpr const char* GetConversionErrorDescription(bool with_description) noexcept {
41 if constexpr (std::is_same_v<TErrorCode, ParseErrorCode>) {
42 return with_description
43 ? "Failed to convert JSON field '{}' with error '{}' ({})"
44 : "Failed to convert JSON field '{}' with error '{}'";
45 } else {
46 return with_description
47 ? "Failed to convert protobuf message field '{}' with error '{}' ({})"
48 : "Failed to convert protobuf message field '{}' with error '{}'";
49 }
50}
51
52} // namespace
53
54template <typename TErrorCode>
55ConversionError<TErrorCode>::ConversionError(
56 const ConversionError<TErrorCode>::ErrorCodeType code,
57 std::string path,
58 std::string_view description
59)
60 : ConversionErrorBase(
61 description.empty()
62 ? fmt::format(GetConversionErrorDescription<TErrorCode>(false), path, GetConversionErrorCodeStr(code))
63 : fmt::format(
64 GetConversionErrorDescription<TErrorCode>(true),
65 path,
66 GetConversionErrorCodeStr(code),
67 description
68 )
69 ),
70 error_info_(code, std::move(path))
71{}
72
73template class ConversionError<ParseErrorCode>;
74template class ConversionError<PrintErrorCode>;
75
76} // namespace protobuf::json
77
78USERVER_NAMESPACE_END