Debian Codegraph @

internal/ctxerr/op_error.go

raw
1 // Copyright (c) 2021 Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package ctxerr
8
9 import (
10 "fmt"
11 "reflect"
12
13 "github.com/maxatome/go-testdeep/internal/types"
14 "github.com/maxatome/go-testdeep/internal/util"
15 )
16
17 // OpBadUsage returns an [*Error] to notice the user she/he passed a bad
18 // parameter to an operator constructor.
19 //
20 // If kind and param's kind name ≠ param's type name:
21 //
22 // usage: {op}{usage}, but received {param type} ({param kind}) as {pos}th parameter
23 //
24 // else
25 //
26 // usage: {op}{usage}, but received {param type} as {pos}th parameter
27 func OpBadUsage(op, usage string, param any, pos int, kind bool) *Error {
28 return OpBad(op, "usage: %s%s, %s", op, usage, util.BadParam(param, pos, kind))
29 }
30
31 // OpTooManyParams returns an [*Error] to notice the user she/he called a
32 // variadic operator constructor with too many parameters.
33 //
34 // usage: {op}{usage}, too many parameters
35 func OpTooManyParams(op, usage string) *Error {
36 return OpBad(op, "usage: %s%s, too many parameters", op, usage)
37 }
38
39 // OpTooFewParams returns an [*Error] to notice the user she/he called a
40 // variadic operator constructor with too few parameters.
41 //
42 // usage: {op}{usage}, too few parameters
43 func OpTooFewParams(op, usage string) *Error {
44 return OpBad(op, "usage: %s%s, too few parameters", op, usage)
45 }
46
47 // OpBad returns an [*Error] to notice the user a bad operator
48 // constructor usage. If len(args) is > 0, s and args are given to
49 // [fmt.Sprintf].
50 func OpBad(op, s string, args ...any) *Error {
51 if len(args) > 0 {
52 s = fmt.Sprintf(s, args...)
53 }
54 return &Error{
55 Message: "bad usage of " + op + " operator",
56 Summary: NewSummary(s),
57 User: true,
58 }
59 }
60
61 // BadKind returns a “bad kind” [*Error], saying got kind does not
62 // match kind(s) listed in okKinds. It is the caller responsibility to
63 // check the kinds compatibility. got can be invalid, in this case it
64 // is displayed as nil.
65 func BadKind(got reflect.Value, okKinds string) *Error {
66 return &Error{
67 Message: "bad kind",
68 Got: types.RawString(types.KindType(got)),
69 Expected: types.RawString(okKinds),
70 }
71 }
72
73 // NilPointer returns a “nil pointer” [*Error], saying got value is a
74 // nil pointer instead of what expected lists. It is the caller
75 // responsibility to check got contains a nil pointer. got should not
76 // be invalid.
77 func NilPointer(got reflect.Value, expected string) *Error {
78 return &Error{
79 Message: "nil pointer",
80 Got: types.RawString("nil " + types.KindType(got)),
81 Expected: types.RawString(expected),
82 }
83 }