This repository was archived by the owner on Sep 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample_test.go
83 lines (67 loc) · 2.03 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2021 The customerror Authors. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package customerror
import (
"errors"
"fmt"
"net/http"
)
// Demonstrates how to create static, and dynamic custom errors, also how to
// check, and instrospect custom errors.
func ExampleNew() {
// Custom static error definition.
ErrMissingID := NewMissingError("id", WithCode("E1010"))
// Some function, for demo purpose.
SomeFunc := func(id string) error {
if id == "" {
// Usage of the custom static error.
return ErrMissingID
}
// Dynamic custom error.
return NewFailedToError("write to disk", WithCode("E1523"))
}
// Case: Without `id`, returns `ErrMissingID`.
if err := SomeFunc(""); err != nil {
fmt.Println(errors.Is(err, ErrMissingID)) // true
var cE *CustomError
if errors.As(err, &cE) {
fmt.Println(cE.StatusCode) // 400
}
fmt.Println(err) // E1010: missing id (400 - Bad Request)
}
// Case: With `id`, returns dynamic error.
if err := SomeFunc("12345"); err != nil {
var cE *CustomError
if errors.As(err, &cE) {
fmt.Println(cE.StatusCode) // 500
}
fmt.Println(err) // E1523: failed to write to disk (500 - Internal Server Error)
}
// output:
// true
// 400
// E1010: missing id
// 500
// E1523: failed to write to disk
}
// Demonstrates how to create static, and dynamic custom errors, also how to
// check, and instrospect custom errors.
//
//nolint:errorlint,forcetypeassert
func ExampleNew_options() {
fmt.Println(
NewMissingError("id", WithCode("E1010"), WithStatusCode(http.StatusNotAcceptable), WithError(errors.New("some error"))).(*CustomError).APIError(),
)
// output:
// E1010: missing id (406 - Not Acceptable). Original Error: some error
}
// Demonstrates error chain. `errB` will wrap `errA` and will be considered the
// same by propagating the chain.
func ExampleNew_is() {
errA := NewMissingError("id")
errB := NewMissingError("name", WithError(errA))
fmt.Println(errors.Is(errB, errA))
// output:
// true
}