• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #ifndef TENSORFLOW_CORE_PLATFORM_ERRORS_H_
17 #define TENSORFLOW_CORE_PLATFORM_ERRORS_H_
18 
19 #include <sstream>
20 
21 #include "absl/strings/str_join.h"
22 #include "tensorflow/core/platform/status.h"
23 #include "tensorflow/core/platform/logging.h"
24 #include "tensorflow/core/platform/macros.h"
25 #include "tensorflow/core/platform/str_util.h"
26 #include "tensorflow/core/platform/strcat.h"
27 
28 namespace tensorflow {
29 namespace errors {
30 
31 typedef ::tensorflow::error::Code Code;
32 
33 namespace internal {
34 
35 // The DECLARE_ERROR macro below only supports types that can be converted
36 // into StrCat's AlphaNum. For the other types we rely on a slower path
37 // through std::stringstream. To add support of a new type, it is enough to
38 // make sure there is an operator<<() for it:
39 //
40 //   std::ostream& operator<<(std::ostream& os, const MyType& foo) {
41 //     os << foo.ToString();
42 //     return os;
43 //   }
44 // Eventually absl::strings will have native support for this and we will be
45 // able to completely remove PrepareForStrCat().
46 template <typename T>
47 typename std::enable_if<!std::is_constructible<strings::AlphaNum, T>::value,
48                         string>::type
PrepareForStrCat(const T & t)49 PrepareForStrCat(const T& t) {
50   std::stringstream ss;
51   ss << t;
52   return ss.str();
53 }
PrepareForStrCat(const strings::AlphaNum & a)54 inline const strings::AlphaNum& PrepareForStrCat(const strings::AlphaNum& a) {
55   return a;
56 }
57 
58 }  // namespace internal
59 
60 // Append some context to an error message.  Each time we append
61 // context put it on a new line, since it is possible for there
62 // to be several layers of additional context.
63 template <typename... Args>
AppendToMessage(::tensorflow::Status * status,Args...args)64 void AppendToMessage(::tensorflow::Status* status, Args... args) {
65   *status = ::tensorflow::Status(
66       status->code(),
67       ::tensorflow::strings::StrCat(status->error_message(), "\n\t", args...));
68 }
69 
70 // For propagating errors when calling a function.
71 #define TF_RETURN_IF_ERROR(...)                          \
72   do {                                                   \
73     ::tensorflow::Status _status = (__VA_ARGS__);        \
74     if (TF_PREDICT_FALSE(!_status.ok())) return _status; \
75   } while (0)
76 
77 #define TF_RETURN_WITH_CONTEXT_IF_ERROR(expr, ...)                  \
78   do {                                                              \
79     ::tensorflow::Status _status = (expr);                          \
80     if (TF_PREDICT_FALSE(!_status.ok())) {                          \
81       ::tensorflow::errors::AppendToMessage(&_status, __VA_ARGS__); \
82       return _status;                                               \
83     }                                                               \
84   } while (0)
85 
86 // Convenience functions for generating and using error status.
87 // Example usage:
88 //   status.Update(errors::InvalidArgument("The ", foo, " isn't right."));
89 //   if (errors::IsInvalidArgument(status)) { ... }
90 //   switch (status.code()) { case error::INVALID_ARGUMENT: ... }
91 
92 #define DECLARE_ERROR(FUNC, CONST)                                       \
93   template <typename... Args>                                            \
94   ::tensorflow::Status FUNC(Args... args) {                              \
95     return ::tensorflow::Status(                                         \
96         ::tensorflow::error::CONST,                                      \
97         ::tensorflow::strings::StrCat(                                   \
98             ::tensorflow::errors::internal::PrepareForStrCat(args)...)); \
99   }                                                                      \
100   inline bool Is##FUNC(const ::tensorflow::Status& status) {             \
101     return status.code() == ::tensorflow::error::CONST;                  \
102   }
103 
DECLARE_ERROR(Cancelled,CANCELLED)104 DECLARE_ERROR(Cancelled, CANCELLED)
105 DECLARE_ERROR(InvalidArgument, INVALID_ARGUMENT)
106 DECLARE_ERROR(NotFound, NOT_FOUND)
107 DECLARE_ERROR(AlreadyExists, ALREADY_EXISTS)
108 DECLARE_ERROR(ResourceExhausted, RESOURCE_EXHAUSTED)
109 DECLARE_ERROR(Unavailable, UNAVAILABLE)
110 DECLARE_ERROR(FailedPrecondition, FAILED_PRECONDITION)
111 DECLARE_ERROR(OutOfRange, OUT_OF_RANGE)
112 DECLARE_ERROR(Unimplemented, UNIMPLEMENTED)
113 DECLARE_ERROR(Internal, INTERNAL)
114 DECLARE_ERROR(Aborted, ABORTED)
115 DECLARE_ERROR(DeadlineExceeded, DEADLINE_EXCEEDED)
116 DECLARE_ERROR(DataLoss, DATA_LOSS)
117 DECLARE_ERROR(Unknown, UNKNOWN)
118 DECLARE_ERROR(PermissionDenied, PERMISSION_DENIED)
119 DECLARE_ERROR(Unauthenticated, UNAUTHENTICATED)
120 
121 #undef DECLARE_ERROR
122 
123 // Produces a formatted string pattern from the name which can uniquely identify
124 // this node upstream to produce an informative error message. The pattern
125 // followed is: {{node <name>}}
126 // Note: The pattern below determines the regex _NODEDEF_NAME_RE in the file
127 // tensorflow/python/client/session.py
128 // LINT.IfChange
129 inline string FormatNodeNameForError(const string& name) {
130   return strings::StrCat("{{node ", name, "}}");
131 }
132 // LINT.ThenChange(//tensorflow/python/client/session.py)
133 template <typename T>
FormatNodeNamesForError(const T & names)134 string FormatNodeNamesForError(const T& names) {
135   return absl::StrJoin(names, ", ", [](string* output, const string& s) {
136     ::tensorflow::strings::StrAppend(output, FormatNodeNameForError(s));
137   });
138 }
139 // LINT.IfChange
FormatColocationNodeForError(const string & name)140 inline string FormatColocationNodeForError(const string& name) {
141   return strings::StrCat("{{colocation_node ", name, "}}");
142 }
143 // LINT.ThenChange(//tensorflow/python/framework/error_interpolation.py)
144 template <typename T>
FormatColocationNodeForError(const T & names)145 string FormatColocationNodeForError(const T& names) {
146   return absl::StrJoin(names, ", ", [](string* output, const string& s) {
147     ::tensorflow::strings::StrAppend(output, FormatColocationNodeForError(s));
148   });
149 }
150 
FormatFunctionForError(const string & name)151 inline string FormatFunctionForError(const string& name) {
152   return strings::StrCat("{{function_node ", name, "}}");
153 }
154 
155 // The CanonicalCode() for non-errors.
156 using ::tensorflow::error::OK;
157 
158 }  // namespace errors
159 }  // namespace tensorflow
160 
161 #endif  // TENSORFLOW_CORE_PLATFORM_ERRORS_H_
162