error.go raw
1 /*
2 * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6 package y
7
8 // This file contains some functions for error handling. Note that we are moving
9 // towards using x.Trace, i.e., rpc tracing using net/tracer. But for now, these
10 // functions are useful for simple checks logged on one machine.
11 // Some common use cases are:
12 // (1) You receive an error from external lib, and would like to check/log fatal.
13 // For this, use x.Check, x.Checkf. These will check for err != nil, which is
14 // more common in Go. If you want to check for boolean being true, use
15 // x.Assert, x.Assertf.
16 // (2) You receive an error from external lib, and would like to pass on with some
17 // stack trace information. In this case, use x.Wrap or x.Wrapf.
18 // (3) You want to generate a new error with stack trace info. Use x.Errorf.
19
20 import (
21 "errors"
22 "fmt"
23 "log"
24 )
25
26 var debugMode = false
27
28 // Check logs fatal if err != nil.
29 func Check(err error) {
30 if err != nil {
31 log.Fatalf("%+v", Wrap(err, ""))
32 }
33 }
34
35 // Check2 acts as convenience wrapper around Check, using the 2nd argument as error.
36 func Check2(_ interface{}, err error) {
37 Check(err)
38 }
39
40 // AssertTrue asserts that b is true. Otherwise, it would log fatal.
41 func AssertTrue(b bool) {
42 if !b {
43 log.Fatalf("%+v", errors.New("Assert failed"))
44 }
45 }
46
47 // AssertTruef is AssertTrue with extra info.
48 func AssertTruef(b bool, format string, args ...interface{}) {
49 if !b {
50 log.Fatalf("%+v", fmt.Errorf(format, args...))
51 }
52 }
53
54 // Wrap wraps errors from external lib.
55 func Wrap(err error, msg string) error {
56 if !debugMode {
57 if err == nil {
58 return nil
59 }
60 return fmt.Errorf("%s err: %+v", msg, err)
61 }
62 return fmt.Errorf("%s: %w", msg, err)
63 }
64
65 // Wrapf is Wrap with extra info.
66 func Wrapf(err error, format string, args ...interface{}) error {
67 return Wrap(err, fmt.Sprintf(format, args...))
68 }
69
70 func CombineErrors(one, other error) error {
71 if one != nil && other != nil {
72 return fmt.Errorf("%v; %v", one, other)
73 }
74 if one != nil && other == nil {
75 return fmt.Errorf("%v", one)
76 }
77 if one == nil && other != nil {
78 return fmt.Errorf("%v", other)
79 }
80 return nil
81 }
82