Status.h 2.3 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
14 15 16

#pragma once

Y
Yu Yang 已提交
17
#include <stdio.h>
Y
Yu Yang 已提交
18 19 20 21 22
#include <memory>
#include <string>

namespace paddle {

23 24 25 26 27
/**
 * Status is Paddle error code. It only contain a std::string as error message.
 * Although Status inherits the std::exception, but do not throw it except you
 * know what you are doing.
 */
Y
Yu Yang 已提交
28 29
class Status final : public std::exception {
public:
30 31 32
  /**
   * Default Status. OK
   */
Y
Yu Yang 已提交
33 34
  Status() noexcept {}

35 36 37 38 39 40 41 42 43 44 45 46 47
  /**
   * @brief Create Status with error message
   * @param msg
   */
  explicit Status(const std::string& msg) : errMsg_(new std::string(msg)) {}

  /**
   * @brief set a error message for status.
   * @param msg
   */
  inline void set(const std::string& msg) noexcept {
    errMsg_.reset(new std::string(msg));
  }
Y
Yu Yang 已提交
48

Y
Yu Yang 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
  /**
   * @brief set a error message for status. Use C style printf
   * @param fmt
   */
  template <typename... ARGS>
  inline void setByPrintf(const char* fmt, ARGS... args) noexcept {
    constexpr size_t bufferSize = 4096;
    char buffer[bufferSize];
    snprintf(buffer, bufferSize, fmt, args...);
    errMsg_.reset(new std::string(buffer));
  }

  /**
   * create a error status by C style printf.
   */
  template <typename... ARGS>
  inline static Status printf(const char* fmt, ARGS... args) noexcept {
    Status s;
    s.setByPrintf(fmt, args...);
    return s;
  }

71 72 73 74
  /**
   * @brief what will return the error message. If status is OK, return nullptr.
   */
  const char* what() const noexcept override {
Y
Yu Yang 已提交
75 76 77 78 79 80 81
    if (errMsg_) {
      return errMsg_->data();
    } else {
      return nullptr;
    }
  }

82 83 84 85
  /**
   * @brief isOK
   * @return true if OK.
   */
Y
Yu Yang 已提交
86 87 88
  inline bool isOK() const noexcept { return errMsg_ == nullptr; }

private:
89
  std::shared_ptr<std::string> errMsg_;
Y
Yu Yang 已提交
90 91 92
};

}  // namespace paddle