Go

Error Handling

Error type, error wrapping, errors.Is, errors.As, custom errors, panic/recover

20 interview questionsยท
Junior
1

What is the interface used to represent errors in Go?

Answer

The error interface is the predefined interface in Go to represent error conditions. It contains a single Error() method that returns a string describing the error. The nil value represents no error. This is the conventional interface used by all standard library packages and Go developers to signal and propagate errors.

2

How to create a simple error with a static message in Go?

Answer

The errors.New() function from the errors package creates a simple error with a static message. It returns an error type that implements the error interface with the provided message. This approach is recommended for creating sentinel errors (predefined errors like os.ErrNotExist) or simple errors without dynamic context. For dynamic messages, use fmt.Errorf().

3

Which function allows creating an error with a dynamically formatted message?

Answer

The fmt.Errorf() function creates an error with a dynamically formatted message using format verbs (like %s, %d, %v). It also supports the special %w verb to wrap an existing error, preserving the error chain for later inspection. This is the recommended method for adding context to errors while keeping the original error.

4

Which format verb allows wrapping an error with fmt.Errorf()?

5

Which function checks if a wrapped error matches a specific error?

+17 interview questions

Master Go for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free