userver: userver/utils/assert.hpp Source File
Loading...
Searching...
No Matches
assert.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/assert.hpp
4/// @brief Assertion macros UASSERT, UASSERT_MSG, UINVARIANT
5/// @ingroup userver_universal
6
7#include <string_view>
8
9USERVER_NAMESPACE_BEGIN
10
11namespace utils::impl {
12
13[[noreturn]] void UASSERT_failed(std::string_view expr, const char* file,
14 unsigned int line, const char* function,
15 std::string_view msg) noexcept;
16
17[[noreturn]] void LogAndThrowInvariantError(std::string_view condition,
18 std::string_view message);
19
20#ifdef NDEBUG
21inline constexpr bool kEnableAssert = false;
22#else
23inline constexpr bool kEnableAssert = true;
24#endif
25
26extern bool dump_stacktrace_on_assert_failure;
27
28} // namespace utils::impl
29
30USERVER_NAMESPACE_END
31
32/// @brief Assertion macro for that aborts execution in DEBUG builds with a
33/// message `msg` and does nothing in release builds
34///
35/// @hideinitializer
36// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
37#define UASSERT_MSG(expr, msg)
38 do {
39 if (USERVER_NAMESPACE::utils::impl::kEnableAssert) {
40 if (expr) {
41 } else {
42 USERVER_NAMESPACE::utils::impl::UASSERT_failed(
43 #expr, __FILE__, __LINE__, __func__, msg);
44 }
45 }
46 } while (0)
47
48/// @brief Assertion macro that aborts execution in DEBUG builds and does
49/// nothing in release builds
50///
51/// @hideinitializer
52// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
53#define UASSERT(expr) UASSERT_MSG(expr, std::string_view{})
54
55/// @brief Asserts in debug builds, throws utils::InvariantError in release
56///
57/// @hideinitializer
58// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
59#define UINVARIANT(condition, message)
60 do {
61 if (condition) {
62 } else {
63 if constexpr (USERVER_NAMESPACE::utils::impl::kEnableAssert) {
64 USERVER_NAMESPACE::utils::impl::UASSERT_failed(
65 #condition, __FILE__, __LINE__, __func__, message);
66 } else {
67 USERVER_NAMESPACE::utils::impl::LogAndThrowInvariantError(#condition,
68 message);
69 }
70 }
71 } while (0)