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(
14 std::string_view expr,
15 const char* file,
16 unsigned int line,
17 const char* function,
18 std::string_view msg
19) noexcept;
20
21[[noreturn]] void LogAndThrowInvariantError(std::string_view condition, std::string_view message);
22
23#ifdef NDEBUG
24inline constexpr bool kEnableAssert = false;
25#else
26inline constexpr bool kEnableAssert = true;
27#endif
28
29extern bool dump_stacktrace_on_assert_failure;
30
31[[noreturn]] void AbortWithStacktrace(std::string_view message) noexcept;
32
33} // namespace utils::impl
34
35USERVER_NAMESPACE_END
36
37/// @brief Assertion macro for that aborts execution in DEBUG builds with a
38/// message `msg` and does nothing in release builds
39///
40/// @hideinitializer
41// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
42#define UASSERT_MSG(expr, msg)
43 do {
44 if (USERVER_NAMESPACE::utils::impl::kEnableAssert) {
45 if (expr) {
46 } else {
47 USERVER_NAMESPACE::utils::impl::UASSERT_failed(#expr, __FILE__, __LINE__, __func__, msg);
48 }
49 }
50 } while (0)
51
52/// @brief Assertion macro that aborts execution in DEBUG builds and does
53/// nothing in release builds
54///
55/// @hideinitializer
56// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
57#define UASSERT(expr) UASSERT_MSG(expr, std::string_view{})
58
59/// @brief Asserts in debug builds, throws utils::InvariantError in release
60///
61/// @hideinitializer
62// NOLINTNEXTLINE (cppcoreguidelines-macro-usage)
63#define UINVARIANT(condition, message)
64 do {
65 if (condition) {
66 } else {
67 if constexpr (USERVER_NAMESPACE::utils::impl::kEnableAssert) {
68 USERVER_NAMESPACE::utils::impl::UASSERT_failed(#condition, __FILE__, __LINE__, __func__, message);
69 } else {
70 USERVER_NAMESPACE::utils::impl::LogAndThrowInvariantError(#condition, message);
71 }
72 }
73 } while (0)