github.com/SamarSidharth/kpt@v0.0.0-20231122062228-c7d747ae3ace/internal/errors/resolver/resolver.go (about)

     1  // Copyright 2021 The kpt Authors
     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  
    15  package resolver
    16  
    17  // errorResolvers is the list of known resolvers for kpt errors.
    18  var errorResolvers []ErrorResolver
    19  
    20  // AddErrorResolver adds the provided error resolver to the list of resolvers
    21  // which will be used to resolve errors.
    22  func AddErrorResolver(er ErrorResolver) {
    23  	errorResolvers = append(errorResolvers, er)
    24  }
    25  
    26  // ResolveError attempts to resolve the provided error into a descriptive
    27  // string which will be displayed to the user. If the last return value is false,
    28  // the error could not be resolved.
    29  func ResolveError(err error) (ResolvedResult, bool) {
    30  	for _, resolver := range errorResolvers {
    31  		rr, found := resolver.Resolve(err)
    32  		// If the exit code hasn't been set, we default it to 1. We should
    33  		// never return exit code 0 for errors.
    34  		if rr.ExitCode == 0 {
    35  			rr.ExitCode = 1
    36  		}
    37  		if found {
    38  			return rr, true
    39  		}
    40  	}
    41  	return ResolvedResult{}, false
    42  }
    43  
    44  type ResolvedResult struct {
    45  	Message  string
    46  	ExitCode int
    47  }
    48  
    49  // ErrorResolver is an interface that allows kpt to resolve an error into
    50  // an error message suitable for the end user.
    51  type ErrorResolver interface {
    52  	Resolve(err error) (ResolvedResult, bool)
    53  }