Debian Codegraph @

api/internal/kusterr/yamlformaterror.go

raw
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package error has contextual error types.
5 package kusterr
6
7 import (
8 "fmt"
9 "strings"
10 )
11
12 // YamlFormatError represents error with yaml file name where json/yaml format error happens.
13 type YamlFormatError struct {
14 Path string
15 ErrorMsg string
16 }
17
18 func (e YamlFormatError) Error() string {
19 return fmt.Sprintf("YAML file [%s] encounters a format error.\n%s\n", e.Path, e.ErrorMsg)
20 }
21
22 // MalformedYamlError represents an error that occurred while trying to decode a given YAML.
23 type MalformedYamlError struct {
24 Path string
25 ErrorMsg string
26 }
27
28 func (e MalformedYamlError) Error() string {
29 return fmt.Sprintf("%s in File: %s", e.ErrorMsg, e.Path)
30 }
31
32 // Handler handles YamlFormatError
33 func Handler(e error, path string) error {
34 if isYAMLSyntaxError(e) {
35 return YamlFormatError{
36 Path: path,
37 ErrorMsg: e.Error(),
38 }
39 }
40 if IsMalformedYAMLError(e) {
41 return MalformedYamlError{
42 Path: path,
43 ErrorMsg: e.Error(),
44 }
45 }
46 return e
47 }
48
49 func isYAMLSyntaxError(e error) bool {
50 return strings.Contains(e.Error(), "error converting YAML to JSON") || strings.Contains(e.Error(), "error unmarshaling JSON")
51 }
52
53 func IsMalformedYAMLError(e error) bool {
54 return strings.Contains(e.Error(), "MalformedYAMLError")
55 }