errcheck checks that you checked errors.

errcheck

errcheck is a program for checking for unchecked errors in go programs.

errcheck

Install

go get -u github.com/kisielk/errcheck

errcheck requires Go 1.12 or newer, and depends on the package go/packages from the golang.org/x/tools repository.

Use

For basic usage, just give the package path of interest as the first argument:

errcheck github.com/kisielk/errcheck/testdata

To check all packages beneath the current directory:

errcheck ./...

Or check all packages in your $GOPATH and $GOROOT:

errcheck all

errcheck also recognizes the following command-line options:

The -tags flag takes a space-separated list of build tags, just like go build. If you are using any custom build tags in your code base, you may need to specify the relevant tags here.

The -asserts flag enables checking for ignored type assertion results. It takes no arguments.

The -blank flag enables checking for assignments of errors to the blank identifier. It takes no arguments.

Excluding functions

Use the -exclude flag to specify a path to a file containing a list of functions to be excluded.

errcheck -exclude errcheck_excludes.txt path/to/package

The file should contain one function signature per line. The format for function signatures is package.FunctionName while for methods it's (package.Receiver).MethodName for value receivers and (*package.Receiver).MethodName for pointer receivers. If the function name is followed by string of form (TYPE), then the the function call is excluded only if the type of the first argument is TYPE. It also accepts a special suffix (os.Stdout) and (os.Stderr), which excludes the function only when the first argument is a literal os.Stdout or os.Stderr.

An example of an exclude file is:

io/ioutil.ReadFile
io.Copy(*bytes.Buffer)
io.Copy(os.Stdout)

// Sometimes we don't care if a HTTP request fails.
(*net/http.Client).Do

By default, the exclude list is combined with an internal list for functions in the Go standard library that have an error return type but are documented to never return an error. To disable the built-in exclude list, pass the -excludeonly flag.

Run errcheck in -verbose mode to see the resulting list of added excludes.

When using vendored dependencies, specify the full import path. For example:

  • Your project's import path is example.com/yourpkg
  • You've vendored example.net/fmt2 as vendor/example.net/fmt2
  • You want to exclude fmt2.Println from error checking

In this case, add this line to your exclude file:

example.com/yourpkg/vendor/example.net/fmt2.Println

Empty lines and lines starting with // are ignored.

The deprecated method

The -ignore flag takes a comma-separated list of pairs of the form package:regex. For each package, the regex describes which functions to ignore within that package. The package may be omitted to have the regex apply to all packages.

For example, you may wish to ignore common operations like Read and Write:

errcheck -ignore '[rR]ead|[wW]rite' path/to/package

or you may wish to ignore common functions like the print variants in fmt:

errcheck -ignore 'fmt:[FS]?[Pp]rint*' path/to/package

The -ignorepkg flag takes a comma-separated list of package import paths to ignore:

errcheck -ignorepkg 'fmt,encoding/binary' path/to/package

Note that this is equivalent to:

errcheck -ignore 'fmt:.*,encoding/binary:.*' path/to/package

If a regex is provided for a package pkg via -ignore, and pkg also appears in the list of packages passed to -ignorepkg, the latter takes precedence; that is, all functions within pkg will be ignored.

Note that by default the fmt package is ignored entirely, unless a regex is specified for it. To disable this, specify a regex that matches nothing:

errcheck -ignore 'fmt:a^' path/to/package

The -ignoretests flag disables checking of _test.go files. It takes no arguments.

Exit Codes

errcheck returns 1 if any problems were found in the checked files. It returns 2 if there were any other failures.

Editor Integration

Emacs

go-errcheck.el integrates errcheck with Emacs by providing a go-errcheck command and customizable variables to automatically pass flags to errcheck.

Vim

vim-go can run errcheck via both its :GoErrCheck and :GoMetaLinter commands.

Comments
  • GO15VENDOREXPERIMENT

    GO15VENDOREXPERIMENT

    Hi, is there any plans for support new env variable GO15VENDOREXPERIMENT for go1.5 in errcheck? errcheck can't recognize a package if it was placed in $GOPATH/src/vendor folder.

    See also for details https://groups.google.com/forum/#!msg/golang-dev/74zjMON9glU/4lWCRDCRZg0J and https://groups.google.com/d/msg/golang-nuts/nnud1w8N3Ik/hPZx32v7DbQJ

    Thank you.

  • Fails if anything uses cgo

    Fails if anything uses cgo

    This is probably a known limitation, but I couldn't find a ticket for it, so here goes:

    errcheck fails if a dependency uses cgo (has import "C").

    Additionally, it seems impossible to ignore this lack of "C" via -ignorepkg (or I just don't know how to use the thing).

    [0 tv@brute ~/src/2013/errcheck-bug-cgo]$ ls
    repro.go
    [0 tv@brute ~/src/2013/errcheck-bug-cgo]$ cat repro.go 
    package main
    
    import _ "github.com/jmhodges/levigo"
    
    func main() {
    }
    [0 tv@brute ~/src/2013/errcheck-bug-cgo]$ errcheck .
    error:failed to check package: could not type check: repro.go:3:10: could not import github.com/jmhodges/levigo (/home/tv/go/src/github.com/jmhodges/levigo/conv.go:4:8: could not import C (cannot find package "C" in any of:
        /home/tv/src/go/src/pkg/C (from $GOROOT)
        /home/tv/go/src/C (from $GOPATH)))
    [1 tv@brute ~/src/2013/errcheck-bug-cgo]$ errcheck -ignorepkg=github.com/jmhodges/levigo .
    error:failed to check package: could not type check: repro.go:3:10: could not import github.com/jmhodges/levigo (/home/tv/go/src/github.com/jmhodges/levigo/cache.go:6:8: could not import C (cannot find package "C" in any of:
        /home/tv/src/go/src/pkg/C (from $GOROOT)
        /home/tv/go/src/C (from $GOPATH)))
    [1 tv@brute ~/src/2013/errcheck-bug-cgo]$ errcheck -ignorepkg=C .
    error:failed to check package: could not type check: repro.go:3:10: could not import github.com/jmhodges/levigo (/home/tv/go/src/github.com/jmhodges/levigo/iterator.go:6:8: could not import C (cannot find package "C" in any of:
        /home/tv/src/go/src/pkg/C (from $GOROOT)
        /home/tv/go/src/C (from $GOPATH)))
    [1 tv@brute ~/src/2013/errcheck-bug-cgo]$ 
    
  • Maintain a list of stdlib functions with irrelevant errors

    Maintain a list of stdlib functions with irrelevant errors

    ~~Either I don't understand the tests, or they're flawed. No matter what marker I did or did not place behind the newly added test cases, the tests always pass. They even pass when I removed the ignores and should've gotten more unchecked errors than expected.~~

  • Check packages concurrently

    Check packages concurrently

    I think this can be done rather straight forward. My only concern is runtime.GOMAXPROCS. Is it OK to set runtime.GOMAXPROCS this way?

    I tested this on a project with ~100 Go files and ~13k lines of code. Went from ~1.0s to ~0.6s. Most of the time is spent in /loader even if all files are in the cache. In my example 0.5s of the 0.6.s is spent there.

  • Add -ignorecomment flag

    Add -ignorecomment flag

    The -ignorecomment flag can be used to ignore calls that have a comment with a specified prefix. Comments are associated with nodes with an ast.CommentMap.

    Here are some examples that will all be ignored with errcheck -asserts -ignorecomment ERRCHECK_IGNORE

    // ERRCHECK_IGNORE: ignore this error because it is always nil.
    aFuncThatReturnsAnError()
    
    // This is a comment preceding the ignorecomment prefix.
    // ERRCHECK_IGNORE: ignore this error because it is always nil.
    aFuncThatReturnsAnError()
    
    aFuncThatReturnsAnError() // ERRCHECK_IGNORE
    
    // ERRCHECK_IGNORE works with defer.
    defer aFuncThatReturnsAnError()
    
    // ERRCHECK_IGNORE also works with type assertions.
    str := anInterface.(string)
    

    Any comment associated with a node can contain the prefix string. See the documentation for ast.NewCommentMap for association rules.

  • Allow comment to suppress complaints

    Allow comment to suppress complaints

    If the code author knows that an error is safe to be ignored, they may omit the return, or assign to underscore, either of which could be caught by errcheck (with -blank in the latter case). It'd be nice if the author could add a comment that would cause errcheck to skip complaining:

    v, _ = cannotFail() // errcheck: this thing can't ever fail, so it's ok to assign to _
    

    This is comparable to "nolint" comments and such in other programming languages.

  • errcheck should not detect

    errcheck should not detect "defer" with error

    It's common in go to use defer with Close() methods.

    file, err := os.Open("/path/to/file")
    if err != nil {
        return err
    }
    defer file.Close()
    

    However errcheck detects this as warning.

  • Fails to build on Go 1.4

    Fails to build on Go 1.4

    We use errcheck for CI tests, for instance: https://travis-ci.org/ncw/rclone/builds/100797264

    Since you require Go 1.5, should we just use another tool, if we want to support 1.4 or lower?

  • Support go modules

    Support go modules

    Use golang.org/x/tools/go/packages to load and type check packages.

    This provides support for projects using go modules to also be able to use errcheck.

    errcheck can support packages that import "C", though there are limitations when run with versions of Go that are earlier than Go 1.11.

    There is also support in go/packages for finding the package that "contains" a file, so should be easy to add support for https://github.com/kisielk/errcheck/issues/106.

  • Can't use errcheck with ./...

    Can't use errcheck with ./...

    Before #44, one could use errcheck like other go tools (errcheck . or errcheck ./...):

    $ cd $GOPATH/src/github.com/kisielk/errcheck
    $ git checkout 125d5c0d507709f2cb85970b145ae03621f6ffe5
    $ go run *.go ./...
    example/main.go:17:10   recover()     // UNCHECKED
    example/main.go:20:15   defer recover() // UNCHECKED
    example/main.go:26:3    a()     // UNCHECKED
    example/main.go:30:3    b()        // UNCHECKED
    example/main.go:35:5    x.a()     // UNCHECKED
    example/main.go:40:7    y.t.a()     // UNCHECKED
    example/main.go:44:9    m1["a"]()     // UNCHECKED
    example/main.go:53:6    go a()    // UNCHECKED
    example/main.go:54:9    defer a() // UNCHECKED
    lib/errcheck.go:138:16  defer rd.Close()
    exit status 1
    

    After #44 :

    $ git checkout master
    $ git rev-parse --verify HEAD
    6523a1db9b999015d645d53a36a450608d6111a2
    $ go run *.go ./...
    error: failed to check package: could not type check: import "./.": import relative to unknown directory
    exit status 2
    

    However, this way still works (fully qualified package name):

    $ go run *.go github.com/kisielk/errcheck/...
    github.com/kisielk/errcheck/example/main.go:17:10   recover()     // UNCHECKED
    github.com/kisielk/errcheck/example/main.go:20:15   defer recover() // UNCHECKED
    github.com/kisielk/errcheck/example/main.go:26:3    a()     // UNCHECKED
    github.com/kisielk/errcheck/example/main.go:30:3    b()        // UNCHECKED
    github.com/kisielk/errcheck/example/main.go:35:5    x.a()     // UNCHECKED
    github.com/kisielk/errcheck/example/main.go:40:7    y.t.a()     // UNCHECKED
    github.com/kisielk/errcheck/example/main.go:44:9    m1["a"]()     // UNCHECKED
    github.com/kisielk/errcheck/example/main.go:53:6    go a()    // UNCHECKED
    github.com/kisielk/errcheck/example/main.go:54:9    defer a() // UNCHECKED
    exit status 1
    
  • Add back support for go modules (fixes #155)

    Add back support for go modules (fixes #155)

    This work was done by @domgreen (see: https://github.com/domgreen/errcheck)

    I've only tested this with Go 1.11 so I'm not sure if older go versions will still work properly.

  • Check for reassignment error

    Check for reassignment error

    In the following code, no linter error is raised. Is this case catchable?

    func doo() (int, int, error) {
        var (
            x, y int
            err  error
        )
        x, err = foo()
        y, err = a(x)
        return x, y, err
    }
    
    func do() (x int, y int, err error) {
        x, err = foo()
        y, err = a(x)
        return x, y, err
    }
    
  • Check error methods on types

    Check error methods on types

    Is there a way to check if the Err method on a type is called?

    For example, the standard library's bufio#Scanner type:

    package main
    
    import (
            "bufio"
            "fmt"
            "os"
    )
    
    func main() {
            scanner := bufio.NewScanner(os.Stdin)
            for scanner.Scan() {
                    fmt.Println(scanner.Text())
            }
            if err := scanner.Err(); err != nil {
                 fmt.Fprintln(os.Stderr, "reading standard input:", err)
            }
    }
    

    Removing the if err := scanner.Err() block is not caught by errcheck.

  • How to exclude builtin functions?

    How to exclude builtin functions?

    Hello!

    # .golangci.yml
    linters-settings:
      errcheck:
        exclude-functions:
          - recover
    
    $ cat example.go
    package main
    
    func main() {
    	defer func() {
    		recover()
    	}()
    }
    
    $ golangci-lint run example.go
    example.go:5:10: Error return value is not checked (errcheck)
    		recover()
    
  • errcheck throws unwarranted error

    errcheck throws unwarranted error

    golang version: >1.17

    The following error occurs when running errcheck: error: failed to check packages: errors while loading package github.com/********-********/****************: [/Users/********/projects/go/src/github.com/********/********/********/********.go:line:col: MaxInt64 not declared by package math]

    To reproduce:

    1. Install golang >v1.17
    2. write code to use any of the constants in the math package (ex: MaxInt64]
    3. Run the errcheck

    Clearly when I drill down into the go library, I see the const.go file under the math package and also see the MaxInt64 const declared. Why would this error still show up?

  • How to run tests in this repo

    How to run tests in this repo

    HI, I want to contribute a feature to errcheck, that is "statement returned error variables must be checked in next statement". This is my commit https://github.com/lance6716/errcheck/commit/43c9b804f2fa62ecd9865c9f440552ecfcd07621

    Now I want to add tests to existing test files, but I'm not familiar with the structure of lint repo. Could someone help me to understand how to write a proper test? Thanks.

A Go linter to check that errors from external packages are wrapped

Wrapcheck A simple Go linter to check that errors from external packages are wrapped during return to help identify the error source during debugging.

Dec 27, 2022
apicompat checks recent changes to a Go project for backwards incompatible changes

Introduction apicompat is a tool to check for the introduction of backwards incompatible changes. apicompat: Guarantees that all consumers of a librar

Dec 24, 2022
This is a style verifier intended to be used with the Gerrit checks plugin.

GERRITFMT This is a style verifier intended to be used with the Gerrit checks plugin. HOW TO USE Install formatters: go install github.com/bazelbuild/

Dec 29, 2022
Fast division, modulus and divisibility checks in Go for divisors known only at runtime.

fastdiv Fast division, modulus and divisibility checks for divisors known only at runtime via the method of: "Faster Remainder by Direct Computation:

Jan 8, 2023
The Golang linter that checks that there is no simultaneous return of `nil` error and an invalid value.

nilnil Checks that there is no simultaneous return of nil error and an invalid value. Installation & usage $ go install github.com/Antonboom/nilnil@la

Dec 14, 2022
Go linter which checks for dangerous unicode character sequences

bidichk - checks for dangerous unicode character sequences bidichk finds dangerous unicode character sequences in Go source files. Considered dangerou

Oct 5, 2022
nostdglobals is a simple Go linter that checks for usages of global variables defined in the go standard library

nostdglobals is a simple Go linter that checks for usages of global variables defined in the go standard library

Feb 17, 2022
Every 10 minutes, memory, cpu and storage usage is checked and if they over 80%, sending alert via email.

linux-alert Every 10 minutes, memory, cpu and storage usage is checked and if they over 80%, sending alert via email. Usage Create .env file from .env

Feb 6, 2022
Drop-in replacement for the standard library errors package and github.com/pkg/errors

Emperror: Errors Drop-in replacement for the standard library errors package and github.com/pkg/errors. This is a single, lightweight library merging

Dec 20, 2022
Common juju errors and functions to annotate errors. Based on juju/errgo

errors import "github.com/juju/errors" The juju/errors provides an easy way to annotate errors without losing the original error context. The exporte

Dec 30, 2022
Linter for errors.Is and errors.As

erris erris is a program for checking that errors are compared or type asserted using go1.13 errors.Is and errors.As functions. Install go get -u gith

Nov 27, 2022
An errors package optimized for the pkg/errors package
An errors package optimized for the pkg/errors package

errors An errors package optimized for the pkg/errors package Use Download and install go get github.com/dobyte/errors API // New Wrapping for errors.

Mar 2, 2022
Go linter that checks types that are json encoded - reports unsupported types and unnecessary error checks

Checks types passed to the json encoding functions. Reports unsupported types and reports occations, where the check for the returned error can be omited.

Oct 7, 2022
sleuth checks that you declared a slice with length and you are trying append to the slice.

sleuth sleuth detects when an append is used on a slice with an initial size. Instruction go install github.com/sivchari/sleuth/cmd/sleuth Usage packa

Sep 15, 2021
Dec 27, 2022
QueryCSV enables you to load CSV files and manipulate them using SQL queries then after you finish you can export the new values to a CSV file
QueryCSV enables you to load CSV files and manipulate them using SQL queries then after you finish you can export the new values to a CSV file

QueryCSV enable you to load CSV files and manipulate them using SQL queries then after you finish you can export the new values to CSV file

Dec 22, 2021
Squizit is a simple tool, that aim to help you get the grade you want, not the one you have learnt for.
Squizit is a simple tool, that aim to help you get the grade you want, not the one you have learnt for.

Squizit is a simple tool, that aim to help you get the grade you want, not the one you have learnt for. Screenshots First, input PIN Then enjoy! Hoste

Mar 11, 2022
The Emperor takes care of all errors personally
The Emperor takes care of all errors personally

The Emperor takes care of all errors personally. Go's philosophy encourages to gracefully handle errors whenever possible, but some times recovering f

Jan 9, 2023
eris provides a better way to handle, trace, and log errors in Go 🎆

eris Package eris provides a better way to handle, trace, and log errors in Go. go get github.com/rotisserie/eris Why you'll want to switch to eris Us

Dec 29, 2022
A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.
A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.

Errors Errors package is a drop-in replacement of the built-in Go errors package with no external dependencies. It lets you create errors of 11 differ

Dec 6, 2022