Alex Vakulenko | c909a9f | 2014-08-14 17:54:04 -0700 | [diff] [blame^] | 1 | // Copyright 2014 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "chromeos/error.h" |
| 6 | |
| 7 | #include <base/logging.h> |
| 8 | #include <base/strings/stringprintf.h> |
| 9 | |
| 10 | using chromeos::Error; |
| 11 | using chromeos::ErrorPtr; |
| 12 | |
| 13 | ErrorPtr Error::Create(const std::string& domain, |
| 14 | const std::string& code, |
| 15 | const std::string& message) { |
| 16 | return Create(domain, code, message, ErrorPtr()); |
| 17 | } |
| 18 | |
| 19 | ErrorPtr Error::Create(const std::string& domain, |
| 20 | const std::string& code, |
| 21 | const std::string& message, |
| 22 | ErrorPtr inner_error) { |
| 23 | LOG(ERROR) << "Error::Create: Domain=" << domain |
| 24 | << ", Code=" << code << ", Message=" << message; |
| 25 | return ErrorPtr(new Error(domain, code, message, std::move(inner_error))); |
| 26 | } |
| 27 | |
| 28 | void Error::AddTo(ErrorPtr* error, const std::string& domain, |
| 29 | const std::string& code, const std::string& message) { |
| 30 | if (error) { |
| 31 | *error = Create(domain, code, message, std::move(*error)); |
| 32 | } else { |
| 33 | // Create already logs the error, but if |error| is nullptr, |
| 34 | // we still want to log the error... |
| 35 | LOG(ERROR) << "Error::Create: Domain=" << domain |
| 36 | << ", Code=" << code << ", Message=" << message; |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | void Error::AddToPrintf(ErrorPtr* error, const std::string& domain, |
| 41 | const std::string& code, const char* format, ...) { |
| 42 | va_list ap; |
| 43 | va_start(ap, format); |
| 44 | std::string message = base::StringPrintV(format, ap); |
| 45 | va_end(ap); |
| 46 | AddTo(error, domain, code, message); |
| 47 | } |
| 48 | |
| 49 | bool Error::HasDomain(const std::string& domain) const { |
| 50 | const Error* err = this; |
| 51 | while (err) { |
| 52 | if (err->GetDomain() == domain) |
| 53 | return true; |
| 54 | err = err->GetInnerError(); |
| 55 | } |
| 56 | return false; |
| 57 | } |
| 58 | |
| 59 | bool Error::HasError(const std::string& domain, const std::string& code) const { |
| 60 | const Error* err = this; |
| 61 | while (err) { |
| 62 | if (err->GetDomain() == domain && err->GetCode() == code) |
| 63 | return true; |
| 64 | err = err->GetInnerError(); |
| 65 | } |
| 66 | return false; |
| 67 | } |
| 68 | |
| 69 | const Error* Error::GetFirstError() const { |
| 70 | const Error* err = this; |
| 71 | while (err->GetInnerError()) |
| 72 | err = err->GetInnerError(); |
| 73 | return err; |
| 74 | } |
| 75 | |
| 76 | Error::Error(const std::string& domain, const std::string& code, |
| 77 | const std::string& message, ErrorPtr inner_error) : |
| 78 | domain_(domain), code_(code), message_(message), |
| 79 | inner_error_(std::move(inner_error)) { |
| 80 | } |