File: format_example_test.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20230522.2e198f4-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 6,404 kB
  • sloc: ansic: 1,900; objc: 276; sh: 272; asm: 48; makefile: 26
file content (47 lines) | stat: -rw-r--r-- 1,303 bytes parent folder | download | duplicates (2)
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
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fmt_test

import (
	"path/filepath"
	"regexp"

	"golang.org/x/exp/errors"
	"golang.org/x/exp/errors/fmt"
)

func baz() error { return errors.New("baz flopped") }
func bar() error { return fmt.Errorf("bar(nameserver 139): %v", baz()) }
func foo() error { return fmt.Errorf("foo: %s", bar()) }

func Example_formatting() {
	err := foo()
	fmt.Println("Error:")
	fmt.Printf("%v\n", err)
	fmt.Println()
	fmt.Println("Detailed error:")
	fmt.Println(stripPath(fmt.Sprintf("%+v\n", err)))
	// Output:
	// Error:
	// foo: bar(nameserver 139): baz flopped
	//
	// Detailed error:
	// foo:
	//     golang.org/x/exp/errors/fmt_test.foo
	//         golang.org/x/exp/errors/fmt/format_example_test.go:17
	//   - bar(nameserver 139):
	//     golang.org/x/exp/errors/fmt_test.bar
	//         golang.org/x/exp/errors/fmt/format_example_test.go:16
	//   - baz flopped:
	//     golang.org/x/exp/errors/fmt_test.baz
	//         golang.org/x/exp/errors/fmt/format_example_test.go:15
}

func stripPath(s string) string {
	rePath := regexp.MustCompile(`( [^ ]*)golang.org`)
	s = rePath.ReplaceAllString(s, " golang.org")
	s = filepath.ToSlash(s)
	return s
}