blob: 869cd536b568f1b1474409358a9314d76954b6ea [file] [log] [blame]
Alex Vakulenkoc909a9f2014-08-14 17:54:04 -07001// 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
Alex Vakulenko15104662014-08-27 11:00:57 -07005#include <chromeos/errors/error.h>
Alex Vakulenkoc909a9f2014-08-14 17:54:04 -07006
7#include <base/logging.h>
8#include <base/strings/stringprintf.h>
9
10using chromeos::Error;
11using chromeos::ErrorPtr;
12
13ErrorPtr 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
19ErrorPtr 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
28void 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
40void 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
49bool 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
59bool 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
69const Error* Error::GetFirstError() const {
70 const Error* err = this;
71 while (err->GetInnerError())
72 err = err->GetInnerError();
73 return err;
74}
75
76Error::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}