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[[noreturn]] void AbortWithStacktrace(std::string_view message) noexcept;
29
30} // namespace utils::impl
31
32USERVER_NAMESPACE_END
33
34/// @brief Assertion macro for that aborts execution in DEBUG builds with a
35/// message `msg` and does nothing in release builds
36///
37/// @hideinitializer
38// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
39#define UASSERT_MSG(expr, msg)
40 do {
41 if (USERVER_NAMESPACE::utils::impl::kEnableAssert) {
42 if (expr) {
43 } else {
44 USERVER_NAMESPACE::utils::impl::UASSERT_failed(
45 #expr, __FILE__, __LINE__, __func__, msg);
46 }
47 }
48 } while (0)
49
50/// @brief Assertion macro that aborts execution in DEBUG builds and does
51/// nothing in release builds
52///
53/// @hideinitializer
54// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
55#define UASSERT(expr) UASSERT_MSG(expr, std::string_view{})
56
57/// @brief Asserts in debug builds, throws utils::InvariantError in release
58///
59/// @hideinitializer
60// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
61#define UINVARIANT(condition, message)
62 do {
63 if (condition) {
64 } else {
65 if constexpr (USERVER_NAMESPACE::utils::impl::kEnableAssert) {
66 USERVER_NAMESPACE::utils::impl::UASSERT_failed(
67 #condition, __FILE__, __LINE__, __func__, message);
68 } else {
69 USERVER_NAMESPACE::utils::impl::LogAndThrowInvariantError(#condition,
70 message);
71 }
72 }
73 } while (0)