1// Copyright 2022 The Bazel Authors. All rights reserved. 2// 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 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 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. 14 15package respipe 16 17import ( 18 "fmt" 19 "strings" 20 21 "context" 22) 23 24const ( 25 ctxErrPrefix = "err-prefix" 26) 27 28// Errorf returns a formatted error with any context sensitive information prefixed to the error 29func Errorf(ctx context.Context, fmts string, a ...interface{}) error { 30 if s, ok := ctx.Value(ctxErrPrefix).(string); ok { 31 return fmt.Errorf(strings.Join([]string{s, fmts}, ""), a...) 32 } 33 return fmt.Errorf(fmts, a...) 34} 35 36// PrefixErr returns a context which adds a prefix to error messages. 37func PrefixErr(ctx context.Context, add string) context.Context { 38 if s, ok := ctx.Value(ctxErrPrefix).(string); ok { 39 return context.WithValue(ctx, ctxErrPrefix, strings.Join([]string{s, add}, "")) 40 } 41 return context.WithValue(ctx, ctxErrPrefix, add) 42 43} 44