MongoDB C++ Driver  legacy-1.1.2
status_with.h
1 // status_with.h
2 
3 /* Copyright 2013 10gen Inc.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #pragma once
19 
20 #include "mongo/base/status.h"
21 
22 namespace mongo {
23 
24 
25 /*
26  * StatusWith is used to return an error or a value
27  * this is designed to make exception code free cleaner by not needing as many out paramters
28  * example:
29  StatusWith<int> fib( int n ) {
30  if ( n < 0 ) return StatusWith<int>( ErrorCodes::BadValue, "paramter to fib has to be >= 0" );
31  if ( n <= 1 ) return StatusWith<int>( 1 );
32  StatusWith<int> a = fib( n - 1 );
33  StatusWith<int> b = fib( n - 2 );
34  if ( !a.isOK() ) return a;
35  if ( !b.isOK() ) return b;
36  return StatusWith<int>( a.getValue() + b.getValue() );
37  }
38 
39  * Note: the value is copied in the current implementation, so should be small (int, int*)
40  * not a vector
41  */
42 template <typename T>
43 class StatusWith {
44 public:
48  StatusWith(ErrorCodes::Error code, const std::string& reason, int location = 0)
49  : _status(Status(code, reason, location)) {}
50 
54  explicit StatusWith(const Status& status) : _status(status) {
55  // verify(( !status.isOK() ); // TODO
56  }
57 
61  explicit StatusWith(const T& t) : _status(Status::OK()), _t(t) {}
62 
63  const T& getValue() const { /* verify( isOK() ); */
64  return _t;
65  } // TODO
66  const Status& getStatus() const {
67  return _status;
68  }
69 
70  bool isOK() const {
71  return _status.isOK();
72  }
73 
74  std::string toString() const {
75  return _status.toString();
76  }
77 
78 private:
79  Status _status;
80  T _t;
81 };
82 }
Status represents an error state or the absence thereof.
Definition: status.h:50
StatusWith(const Status &status)
for the error case
Definition: status_with.h:54
Utility functions for parsing numbers from strings.
Definition: compare_numbers.h:20
Definition: status_with.h:43
StatusWith(const T &t)
for the OK case
Definition: status_with.h:61
MONGO_CLIENT_API Status(MONGO_CLIENT_FUNC *saslClientAuthenticate)(DBClientWithCommands *client
Attempts to authenticate "client" using the SASL protocol.
StatusWith(ErrorCodes::Error code, const std::string &reason, int location=0)
for the error case
Definition: status_with.h:48