1 // Copyright 2017 Google LLC
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
20 "google.golang.org/api/googleapi"
21 "google.golang.org/grpc/status"
24 // Annotate prepends msg to the error message in err, attempting
25 // to preserve other information in err, like an error code.
27 // Annotate panics if err is nil.
29 // Annotate knows about these error types:
30 // - "google.golang.org/grpc/status".Status
31 // - "google.golang.org/api/googleapi".Error
32 // If the error is not one of these types, Annotate behaves
34 // fmt.Errorf("%s: %v", msg, err)
35 func Annotate(err error, msg string) error {
37 panic("Annotate called with nil")
39 if s, ok := status.FromError(err); ok {
41 p.Message = msg + ": " + p.Message
42 return status.ErrorProto(p)
44 if g, ok := err.(*googleapi.Error); ok {
45 g.Message = msg + ": " + g.Message
48 return fmt.Errorf("%s: %v", msg, err)
51 // Annotatef uses format and args to format a string, then calls Annotate.
52 func Annotatef(err error, format string, args ...interface{}) error {
53 return Annotate(err, fmt.Sprintf(format, args...))