• Stars
    star
    167
  • Rank 225,412 (Top 5 %)
  • Language
    Go
  • License
    BSD 3-Clause "New...
  • Created over 2 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simplified error handling in Go

Try: Simplified Error Handling in Go

GoDev Build Status

This module reduces the syntactic cost of error handling in Go.

Example usage in a main program:

func main() {
    defer try.F(log.Fatal)
    b := try.E1(os.ReadFile(...))
    var v any
    try.E(json.Unmarshal(b, &v))
    ...
}

Example usage in a unit test:

func Test(t *testing.T) {
    defer try.F(t.Fatal)
    db := try.E1(setdb.Open(...))
    defer db.Close()
    ...
    try.E(db.Commit())
}

Code before try:

func (a *MixedArray) UnmarshalNext(uo json.UnmarshalOptions, d *json.Decoder) error {
    switch t, err := d.ReadToken(); {
    case err != nil:
        return err
    case t.Kind() != '[':
        return fmt.Errorf("got %v, expecting array start", t.Kind())
    }

    if err := uo.UnmarshalNext(d, &a.Scalar); err != nil {
        return err
    }
    if err := uo.UnmarshalNext(d, &a.Slice); err != nil {
        return err
    }
    if err := uo.UnmarshalNext(d, &a.Map); err != nil {
        return err
    }

    switch t, err := d.ReadToken(); {
    case err != nil:
        return err
    case t.Kind() != ']':
        return fmt.Errorf("got %v, expecting array end", t.Kind())
    }
    return nil
}

Code after try:

func (a *MixedArray) UnmarshalNext(uo json.UnmarshalOptions, d *json.Decoder) (err error) {
    defer try.Handle(&err)
    if t := try.E1(d.ReadToken()); t.Kind() != '[' {
        return fmt.Errorf("found %v, expecting array start", t.Kind())
    }
    try.E(uo.UnmarshalNext(d, &a.Scalar))
    try.E(uo.UnmarshalNext(d, &a.Slice))
    try.E(uo.UnmarshalNext(d, &a.Map))
    if t := try.E1(d.ReadToken()); t.Kind() != ']' {
        return fmt.Errorf("found %v, expecting array end", t.Kind())
    }
    return nil
}

See the documentation for more information.

Install

go get -u github.com/dsnet/try

Semgrep rules

These semgrep rules can help prevent bugs and abuse:

rules:
  - id: non-deferred-try-handle
    patterns:
      - pattern-either:
          - pattern: try.F(...)
          - pattern: try.Handle(...)
          - pattern: try.HandleF(...)
          - pattern: try.Recover(...)
      - pattern-not: defer try.F(...)
      - pattern-not: defer try.Handle(...)
      - pattern-not: defer try.HandleF(...)
      - pattern-not: defer try.Recover(...)
    message: Calls to try handlers must be deferred
    severity: ERROR
    languages:
      - go
  - id: missing-try-handler
    patterns:
      - pattern-either:
          - pattern: try.E(...)
          - pattern: try.E1(...)
          - pattern: try.E2(...)
          - pattern: try.E3(...)
          - pattern: try.E4(...)
      - pattern-not-inside: |
          ...
          defer try.F(...)
          ...
      - pattern-not-inside: |
          ...
          defer try.Handle(...)
          ...
      - pattern-not-inside: |
          ...
          defer try.HandleF(...)
          ...
      - pattern-not-inside: |
          ...
          defer try.Recover(...)
          ...
    message: Calls to try.E[n] must have a matching function-local handler
    severity: ERROR
    languages:
      - go

License

BSD - See LICENSE file

More Repositories

1

compress

Collection of compression related Go packages.
Go
399
star
2

udptunnel

Daemon for creating a simple VPN over UDP.
Go
173
star
3

termijack

TermiJack surreptitiously hijacks standard streams (stdin, stdout, and/or stderr) from an already running process.
Python
171
star
4

sshtunnel

SSH daemon for creating forward and reverse tunnels.
Go
72
star
5

motd-generator

Custom message-of-the-day (MOTD) generator intended to be informative about the system you are logging in to.
Python
44
star
6

golib

Collection of mostly unrelated helper Go packages.
Go
30
star
7

playground

Locally hosted Go playground for more advanced functionality.
Go
20
star
8

gotab

Simple bash tab completion for the go command.
Go
10
star
9

tri-approx

Experiments in fixed-point approximation of trigonometric functions.
C
9
star
10

zsync

Daemon for replicating ZFS datasets.
Go
7
star
11

matrix-transpose

Experiments in the efficient transpose of bit-matrices.
C
7
star
12

mario-doorbell

Custom doorbell design that plays the Mario coin sounds upon every press.
C
5
star
13

generate-gallery

Tool for generating static .html files with thumbnails for all images and videos in a directory
Go
5
star
14

codebreaker

Solver for Codenames, a boardgame by Vladimír Chvátil
HTML
5
star
15

godoc

Go
5
star
16

crypto

Collection of crypto related Go packages.
Go
4
star
17

file-server

Simple HTTP file server.
JavaScript
2
star
18

dns-updater

Dynamically updates DNS records on Rackspace if it differs from the currently assigned external IP address.
Python
1
star
19

remote-keyless-system

Wireless remote keyless system to unlock the dorm door.
C
1
star