$darkmode
error.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2020 Robert Bosch GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * SPDX-License-Identifier: Apache-2.0
17  */
23 #pragma once
24 
25 #include <stdexcept> // for exception
26 #include <string> // for string
27 #include <string_view> // for string
28 
29 #include <fmt/format.h> // for fmt::format
30 
31 namespace cloe {
32 
33 class Error;
34 
35 class Error : public std::exception {
36  public:
37  Error(std::string_view what) : err_(what.data()) {}
38 
39  template <typename... Args>
40  Error(std::string_view format, Args&&... args)
41  : err_(fmt::format(fmt::runtime(format), std::forward<Args>(args)...)) {}
42 
43  virtual ~Error() noexcept = default;
44 
45  const char* what() const noexcept override { return err_.what(); }
46 
47  bool has_explanation() const { return !explanation_.empty(); }
48 
49  void set_explanation(std::string explanation);
50 
51  template <typename... Args>
52  void set_explanation(std::string_view format, Args&&... args) {
53  set_explanation(fmt::format(fmt::runtime(format), std::forward<Args>(args)...));
54  }
55 
56  const std::string& explanation() const { return explanation_; }
57 
58  Error explanation(std::string explanation) && {
59  set_explanation(std::move(explanation));
60  return std::move(*this);
61  }
62 
63  template <typename... Args>
64  Error explanation(std::string_view format, Args&&... args) && {
65  set_explanation(fmt::format(fmt::runtime(format), std::forward<Args>(args)...));
66  return std::move(*this);
67  }
68 
69  private:
70  std::runtime_error err_;
71  std::string explanation_;
72 };
73 
80 class ConcludedError : public std::exception {
81  public:
82  explicit ConcludedError(std::exception& e) : cause_(e) {}
83  virtual ~ConcludedError() noexcept = default;
84 
85  std::exception& cause() const noexcept { return cause_; }
86  const char* what() const noexcept override { return cause_.what(); }
87 
88  private:
89  std::exception& cause_;
90 };
91 
92 } // namespace cloe
Definition: error.hpp:80
Definition: error.hpp:35