{"id":809,"date":"2026-10-08T11:00:00","date_gmt":"2026-10-08T05:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/"},"modified":"2026-11-29T01:29:31","modified_gmt":"2026-11-28T19:59:31","slug":"go-error-handling-programs","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/","title":{"rendered":"Go Error Handling Programs: Wrap, errors.Is, errors.As, Recover"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Go error handling programs show how Go reports and deals with problems, such as a missing file, bad input or a failed payment. Go has no exceptions: functions return an <code>error<\/code> value, and you check it right away. In this post, you will write fourteen error handling programs with their exact output, covering custom errors, wrapping, <code>errors.Is<\/code>, <code>errors.As<\/code>, <code>errors.Join<\/code>, panic and recover, followed by the error questions interviewers ask most.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This post builds on our <a href=\"https:\/\/smitabharat.com\/blog\/go-interface-programs\/\">Go interface programs<\/a>, because <code>error<\/code> is an interface. For the theory, read the <a href=\"https:\/\/smitabharat.com\/blog\/go-error-handling-guide\/\">Go error handling guide<\/a>, <a href=\"https:\/\/smitabharat.com\/blog\/go-error-wrapping-guide\/\">Go error wrapping<\/a> and <a href=\"https:\/\/smitabharat.com\/blog\/go-defer-panic-recover\/\">Go defer, panic and recover<\/a>. All programs were tested on Go 1.27.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What are Go Error Handling Programs?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go error handling programs return an <code>error<\/code> as the last result of a function. If the error is <code>nil<\/code>, everything worked. If it is not <code>nil<\/code>, the caller decides what to do: retry, add context, return it up, or show a message.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of a delivery app. When the rider cannot find the address, the app does not crash. It shows &#8220;address not found&#8221; and lets you fix it. Go errors work the same way: they are normal values that carry a message back to whoever can fix the problem.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Go Error Handling Programs Matter<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Every real program meets errors: files go missing, networks fail and users type bad data. Go makes these failures visible in the code, so you cannot ignore them by accident. Good Go error handling programs give clear messages and still let callers check what went wrong.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Reliability:<\/strong> checking errors stops bad data from spreading.<\/li>\n\n\n<li><strong>Debugging:<\/strong> wrapped errors show the full path of a failure.<\/li>\n\n\n<li><strong>Interviews:<\/strong> <code>errors.Is<\/code> vs <code>errors.As<\/code>, panic vs error and the nil error trap are common questions.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How Go Error Handling Programs Work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A function returns <code>(result, error)<\/code>. The caller checks <code>if err != nil<\/code> straight after the call. To add context, it wraps the error with <code>fmt.Errorf(\"...: %w\", err)<\/code> and returns it. Higher up, code uses <code>errors.Is<\/code> or <code>errors.As<\/code> to look inside the chain.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-1.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-1-1024x640.png\" alt=\"Go error handling programs diagram showing an error created, wrapped with context and checked with errors.Is\" class=\"wp-image-786\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">A low-level error is wrapped with context at each layer, and the top layer checks the chain with errors.Is or errors.As.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The table below lists the error tools in this post.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Tool<\/th><th>What it does<\/th><th>Since<\/th><\/tr><\/thead><tbody><tr><td>errors.New(&#8220;msg&#8221;)<\/td><td>Creates a simple error<\/td><td>Always<\/td><\/tr><tr><td>fmt.Errorf(&#8220;ctx: %w&#8221;, err)<\/td><td>Wraps an error with context<\/td><td>Go 1.13<\/td><\/tr><tr><td>errors.Is(err, target)<\/td><td>Checks for a specific error in the chain<\/td><td>Go 1.13<\/td><\/tr><tr><td>errors.As(err, &amp;target)<\/td><td>Finds an error of a given type<\/td><td>Go 1.13<\/td><\/tr><tr><td>errors.Unwrap(err)<\/td><td>Gets the next error in the chain<\/td><td>Go 1.13<\/td><\/tr><tr><td>errors.Join(e1, e2)<\/td><td>Combines several errors<\/td><td>Go 1.20<\/td><\/tr><tr><td>panic \/ recover<\/td><td>Handles truly unexpected failures<\/td><td>Always<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Go Error Handling Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These first Go error handling programs create and check errors.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 1: errors.New, the Start of All Go Error Handling Programs<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Start with the smallest idea. A function returns an error when something is wrong, and <code>nil<\/code> when all is fine.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ checkAge returns an error if the age is below zero.\nfunc checkAge(age int) error {\n    if age &lt; 0 {\n        return errors.New(\"age cannot be negative\") \/\/ errors.New makes a simple error\n    }\n    return nil \/\/ nil means \"no error\"\n}\n\nfunc main() {\n    err := checkAge(25) \/\/ err is the error value\n    fmt.Println(\"Check 25:\", err)\n\n    err = checkAge(-3)\n    if err != nil { \/\/ the usual Go check\n        fmt.Println(\"Check -3 failed:\", err)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Check 25: &lt;nil&gt;\nCheck -3 failed: age cannot be negative<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>checkAge<\/code> has <code>error<\/code> as its return type. For 25 it returns <code>nil<\/code>, which prints as <code>&lt;nil&gt;<\/code>. For -3 it returns an error, so the <code>if err != nil<\/code> block runs and prints the message.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 2: Return and Check an Error<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ withdraw takes money out and returns the new balance, or an error.\nfunc withdraw(balance, amount int) (int, error) {\n    if amount &gt; balance {\n        return balance, errors.New(\"insufficient balance\") \/\/ keep the old balance\n    }\n    return balance - amount, nil\n}\n\nfunc main() {\n    balance, err := withdraw(1000, 300)\n    fmt.Println(balance, err)\n\n    balance, err = withdraw(balance, 900) \/\/ = reuses the variables, := would make new ones\n    if err != nil {\n        fmt.Println(\"Error:\", err)\n    }\n    fmt.Println(\"Balance:\", balance)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>700 &lt;nil&gt;\nError: insufficient balance\nBalance: 700<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The function returns two values: the balance and an error. We return the old balance with the error, so the caller still has a sensible value. The <code>if err != nil<\/code> check comes right after the call.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 3: Sentinel Errors with errors.Is<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A sentinel error is a named error value that callers can check for.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ ErrNotFound is a named error that callers can compare against.\nvar ErrNotFound = errors.New(\"user not found\")\n\n\/\/ findUser returns the name for an ID, or ErrNotFound.\nfunc findUser(id int) (string, error) {\n    users := map[int]string{1: \"Asha\", 2: \"Ravi\"}\n    name, ok := users[id] \/\/ ok is true if the ID is in the map\n    if !ok {\n        return \"\", ErrNotFound\n    }\n    return name, nil\n}\n\nfunc main() {\n    for _, id := range []int{1, 7} {\n        name, err := findUser(id)\n        if errors.Is(err, ErrNotFound) { \/\/ is this our \"not found\" error?\n            fmt.Println(id, \"-&gt; please sign up\")\n            continue \/\/ skip to the next ID\n        }\n        fmt.Println(id, \"-&gt;\", name)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1 -&gt; Asha\n7 -&gt; please sign up<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">ID 1 is in the map, so it prints the name. ID 7 is missing, so <code>findUser<\/code> returns <code>ErrNotFound<\/code>. Callers compare with <code>errors.Is<\/code> instead of matching the message text, so you can change the wording later.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 4: Wrap Errors with %w<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ ErrTimeout is the low-level error.\nvar ErrTimeout = errors.New(\"timeout\")\n\n\/\/ callBank always fails in this example.\nfunc callBank() error {\n    return ErrTimeout\n}\n\n\/\/ processPayment adds the order ID to any error from callBank.\nfunc processPayment(orderID int) error {\n    err := callBank()\n    if err != nil {\n        return fmt.Errorf(\"payment for order %d: %w\", orderID, err) \/\/ %w wraps the original error\n    }\n    return nil\n}\n\nfunc main() {\n    err := processPayment(501)\n    fmt.Println(err)\n    fmt.Println(errors.Is(err, ErrTimeout))        \/\/ look inside the wrapper\n    fmt.Println(errors.Unwrap(err) == ErrTimeout) \/\/ Unwrap removes one layer\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>payment for order 501: timeout\ntrue\ntrue<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>%w<\/code> keeps the original error inside the new one. So the message gains context, and <code>errors.Is<\/code> can still find <code>ErrTimeout<\/code>. <code>errors.Unwrap<\/code> takes off the outer layer and gives back the original.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Custom Go Error Handling Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In Go error handling programs, custom error types carry extra details that callers can use.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 5: A Custom Error Type with errors.As<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ ValidationError says which field is wrong and why.\ntype ValidationError struct {\n    Field string\n    Issue string\n}\n\n\/\/ Error makes *ValidationError satisfy the error interface.\nfunc (validationError *ValidationError) Error() string {\n    return validationError.Field + \": \" + validationError.Issue\n}\n\n\/\/ register checks the age and returns a wrapped ValidationError.\nfunc register(email string, age int) error {\n    if age &lt; 18 {\n        problem := &amp;ValidationError{\"age\", \"must be 18 or older\"}\n        return fmt.Errorf(\"register: %w\", problem)\n    }\n    return nil\n}\n\nfunc main() {\n    err := register(\"asha@example.com\", 16)\n    var target *ValidationError     \/\/ errors.As will fill this in\n    if errors.As(err, &amp;target) {    \/\/ pass the address so As can store the result\n        fmt.Println(\"Field:\", target.Field)\n        fmt.Println(\"Issue:\", target.Issue)\n    }\n    fmt.Println(err)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Field: age\nIssue: must be 18 or older\nregister: age: must be 18 or older<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>errors.As<\/code> walks the chain and fills <code>target<\/code> when it finds a <code>*ValidationError<\/code>. Then you can read its fields, which a plain string could never give you.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 6: Combine Errors with errors.Join<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"strings\"\n)\n\n\/\/ ErrEmpty is returned when the name is blank.\nvar ErrEmpty = errors.New(\"name is empty\")\n\n\/\/ validate collects every problem instead of stopping at the first one.\nfunc validate(name, email string) error {\n    var problems []error \/\/ starts empty\n    if name == \"\" {\n        problems = append(problems, ErrEmpty)\n    }\n    if !strings.Contains(email, \"@\") {\n        problems = append(problems, fmt.Errorf(\"email %q is invalid\", email))\n    }\n    return errors.Join(problems...) \/\/ ... passes each item in the slice\n}\n\nfunc main() {\n    err := validate(\"\", \"asha.example.com\")\n    fmt.Println(err)\n    fmt.Println(errors.Is(err, ErrEmpty))\n    fmt.Println(validate(\"Asha\", \"a@b.com\") == nil)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>name is empty\nemail \"asha.example.com\" is invalid\ntrue\ntrue<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>validate<\/code> adds each problem to a slice, then joins them into one error. <code>errors.Join<\/code> puts each error on its own line. It returns nil when the list is empty, so a valid form gives no error at all.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 7: Print the Whole Error Chain<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\nfunc main() {\n    \/\/ Step 1: build three layers of errors.\n    diskError := errors.New(\"disk full\")\n    saveError := fmt.Errorf(\"save invoice: %w\", diskError)\n    checkoutError := fmt.Errorf(\"checkout: %w\", saveError)\n\n    \/\/ Step 2: print each layer, from the outside in.\n    current := checkoutError\n    for current != nil {\n        fmt.Println(\"-\", current)\n        current = errors.Unwrap(current) \/\/ move one layer down; nil at the bottom\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>- checkout: save invoice: disk full\n- save invoice: disk full\n- disk full<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each <code>Unwrap<\/code> call peels off one layer. The loop stops when there is nothing left, because <code>Unwrap<\/code> returns nil. This is a handy way to see how a deep error reached the top.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Real-World Go Error Handling Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go error handling programs deal with files, input and retries.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 8: File Not Found with fs.ErrNotExist<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"io\/fs\"\n    \"os\"\n)\n\nfunc main() {\n    _, err := os.Open(\"missing-report.txt\") \/\/ _ ignores the file, we only need err\n\n    \/\/ Is this a \"file does not exist\" error?\n    if errors.Is(err, fs.ErrNotExist) {\n        fmt.Println(\"File does not exist, creating a new one\")\n    }\n\n    \/\/ Get the detailed path error to read its fields.\n    var pathError *fs.PathError\n    if errors.As(err, &amp;pathError) {\n        fmt.Println(\"Operation:\", pathError.Op, \"Path:\", pathError.Path)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>File does not exist, creating a new one\nOperation: open Path: missing-report.txt<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>os.Open<\/code> fails because the file is missing. The standard library wraps its errors too. So the same <code>errors.Is<\/code> and <code>errors.As<\/code> tools work on file and network errors.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 9: Convert Text to a Number Safely<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This is an error you will meet on day one. The text may not be a number at all.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    for _, text := range []string{\"42\", \"abc\"} {\n        number, err := strconv.Atoi(text) \/\/ Atoi turns text into an int\n        if err != nil {\n            fmt.Println(\"Not a number:\", text)\n            continue\n        }\n        fmt.Println(\"Got the number\", number)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Got the number 42\nNot a number: abc<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>strconv.Atoi<\/code> returns a number and an error. For &#8220;42&#8221; the error is nil, so you can use the number. For &#8220;abc&#8221; it returns an error, and the program prints a friendly message instead of crashing.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 10: Parse Input and Report Bad Values<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\n\/\/ parseAges turns a list of texts into ages, or says which item is bad.\nfunc parseAges(input []string) ([]int, error) {\n    var ages []int\n    for i, text := range input { \/\/ i is the position, text is the value\n        age, err := strconv.Atoi(text)\n        if err != nil {\n            return nil, fmt.Errorf(\"item %d: %w\", i, err) \/\/ say which item failed\n        }\n        ages = append(ages, age)\n    }\n    return ages, nil\n}\n\nfunc main() {\n    fmt.Println(parseAges([]string{\"21\", \"34\", \"19\"}))\n    fmt.Println(parseAges([]string{\"21\", \"thirty\", \"19\"}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[21 34 19] &lt;nil&gt;\n[] item 1: strconv.Atoi: parsing \"thirty\": invalid syntax<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The loop converts each text and stops at the first bad one. The error tells you exactly which item failed and why. This kind of message saves a lot of debugging time.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 11: Retry on a Temporary Error<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ ErrBusy means \"try again later\".\nvar ErrBusy = errors.New(\"server busy\")\n\n\/\/ Server fails the first two calls, then works.\ntype Server struct {\n    attempts int \/\/ how many times Call has run\n}\n\n\/\/ Call counts the attempt and returns ErrBusy until the third try.\nfunc (server *Server) Call() error {\n    server.attempts++\n    if server.attempts &lt; 3 {\n        return ErrBusy\n    }\n    return nil\n}\n\nfunc main() {\n    server := &amp;Server{}\n    for try := 1; try &lt;= 5; try++ {\n        err := server.Call()\n        if err == nil {\n            fmt.Println(\"Success on try\", try)\n            break \/\/ stop the loop, we are done\n        }\n        if errors.Is(err, ErrBusy) {\n            fmt.Println(\"Try\", try, \"failed:\", err)\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Try 1 failed: server busy\nTry 2 failed: server busy\nSuccess on try 3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The loop calls the server up to five times. The first two calls return <code>ErrBusy<\/code>, so we print and try again. On the third call the error is nil, and <code>break<\/code> ends the loop. In real code, you would also wait a little longer before each new try.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Panic and Recover in Go Error Handling Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>panic<\/code> stops normal flow, and <code>recover<\/code> inside a deferred function can catch it. Use them only for real bugs or impossible states, not for normal errors.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 12: Recover from a Panic<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ safeDivide divides two numbers and turns a panic into an error.\nfunc safeDivide(dividend, divisor int) (result int, err error) { \/\/ named results\n    \/\/ defer runs this function when safeDivide ends, even after a panic.\n    defer func() {\n        recovered := recover() \/\/ nil if there was no panic\n        if recovered != nil {\n            err = fmt.Errorf(\"recovered: %v\", recovered)\n        }\n    }()\n    return dividend \/ divisor, nil \/\/ dividing by 0 panics here\n}\n\nfunc main() {\n    fmt.Println(safeDivide(10, 2))\n    fmt.Println(safeDivide(10, 0))\n    fmt.Println(\"program keeps running\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>5 &lt;nil&gt;\n0 recovered: runtime error: integer divide by zero\nprogram keeps running<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Dividing by zero causes a panic. The deferred function catches it with <code>recover<\/code> and turns it into a normal error by setting the named result <code>err<\/code>. Without <code>recover<\/code>, the whole program would crash.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 13: Defers Still Run During a Panic<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ work sets up two cleanups, then panics.\nfunc work() {\n    defer fmt.Println(\"cleanup: close file\")   \/\/ runs second\n    defer fmt.Println(\"cleanup: release lock\") \/\/ runs first (last in, first out)\n    panic(\"something went badly wrong\")\n}\n\nfunc main() {\n    defer func() {\n        fmt.Println(\"main recovered:\", recover())\n    }()\n    work()\n    fmt.Println(\"never printed\") \/\/ the panic skips this line\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>cleanup: release lock\ncleanup: close file\nmain recovered: something went badly wrong<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">As the panic travels up, every deferred call runs in reverse order. Then <code>main<\/code> catches the panic with <code>recover<\/code>. That is why <code>defer<\/code> is the right place for cleanup.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 14: Must Functions Panic on Setup Errors<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n)\n\nfunc main() {\n    \/\/ MustCompile panics if the pattern is wrong; fine for fixed patterns.\n    pinPattern := regexp.MustCompile(`^\\d{6}$`) \/\/ exactly six digits\n    fmt.Println(pinPattern.MatchString(\"411001\"), pinPattern.MatchString(\"4110\"))\n\n    \/\/ Compile returns an error instead of panicking.\n    _, err := regexp.Compile(`[a-z`)\n    fmt.Println(err)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true false\nerror parsing regexp: missing closing ]: `[a-z`<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>MustCompile<\/code> is safe here because the pattern is fixed in the code. <code>Must<\/code> functions are for values like this, where a mistake is a bug you want to see at once. For user input, use the version that returns an error.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Errors vs Panic in Go Error Handling Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Every one of the Go error handling programs above makes one choice. The diagram and table below show when to return an error and when to panic.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-2.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-2-1024x640.png\" alt=\"Go error handling programs comparison of returning errors and using panic\" class=\"wp-image-787\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">Return errors for expected problems, and keep panic for bugs and states that should never happen.<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Return an error<\/th><th>panic<\/th><\/tr><\/thead><tbody><tr><td>Used for<\/td><td>Expected problems<\/td><td>Bugs and impossible states<\/td><\/tr><tr><td>Example<\/td><td>File missing, bad input<\/td><td>Nil map write, broken setup<\/td><\/tr><tr><td>Caller sees it<\/td><td>In the return value<\/td><td>Only through recover<\/td><\/tr><tr><td>Program keeps running<\/td><td>Yes<\/td><td>No, unless recovered<\/td><\/tr><tr><td>Normal in libraries<\/td><td>Yes<\/td><td>Rarely, avoid it<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">In short, return errors for anything a user or the network can cause. Panic only when continuing would be worse than stopping.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes in Go Error Handling Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Ignoring errors with _:<\/strong> a skipped error often turns into a confusing bug later.<\/li>\n\n\n<li><strong>Using %v instead of %w:<\/strong> <code>%v<\/code> loses the original error, so <code>errors.Is<\/code> stops working.<\/li>\n\n\n<li><strong>Comparing message strings:<\/strong> wording can change, so compare with <code>errors.Is<\/code> or <code>errors.As<\/code>.<\/li>\n\n\n<li><strong>Returning a typed nil pointer as error:<\/strong> an interface holding a nil pointer is not nil.<\/li>\n\n\n<li><strong>Using panic for normal failures:<\/strong> callers cannot handle it with a simple <code>if<\/code>.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Go Error Handling Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Check errors right after the call<\/strong>, before you use the result.<\/li>\n\n\n<li><strong>Add context when you return<\/strong>, such as <code>fmt.Errorf(\"load config: %w\", err)<\/code>.<\/li>\n\n\n<li><strong>Use sentinel errors or custom types<\/strong> for errors callers need to check.<\/li>\n\n\n<li><strong>Handle each error once<\/strong>: either log it or return it, not both.<\/li>\n\n\n<li><strong>Keep error messages lower case<\/strong> and without a full stop, as Go style suggests.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Go Error Handling Programs Interview Questions and Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Interviewers ask these Go error handling programs more than any other error questions. Each program is complete, with real output from Go 1.27.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Error Basics Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1. What is the error type in Go?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is a built-in interface with one method: <code>Error() string<\/code>. Any type with that method can be used as an error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2. Why does Go not have exceptions?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go treats errors as normal values, so the code shows every place that can fail. This makes failure paths easy to read and test. <code>panic<\/code> exists, but only for truly exceptional cases.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3. What is the difference between errors.Is and errors.As?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>errors.Is<\/code> checks whether a specific error value, such as <code>ErrNotFound<\/code>, is in the chain. <code>errors.As<\/code> looks for an error of a specific type and gives you that value, so you can read its fields.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Wrapping Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ ErrLimit is the original error.\nvar ErrLimit = errors.New(\"limit reached\")\n\nfunc main() {\n    withV := fmt.Errorf(\"upload: %v\", ErrLimit) \/\/ %v copies only the text\n    withW := fmt.Errorf(\"upload: %w\", ErrLimit) \/\/ %w keeps the original error inside\n    fmt.Println(withV, \"|\", withW)\n    fmt.Println(errors.Is(withV, ErrLimit), errors.Is(withW, ErrLimit))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>upload: limit reached | upload: limit reached\nfalse true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Both messages look the same. But only <code>%w<\/code> keeps the original error inside, so only <code>withW<\/code> passes the <code>errors.Is<\/code> check.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\nfunc main() {\n    first := errors.New(\"same text\")\n    second := errors.New(\"same text\")\n    fmt.Println(first == second, first.Error() == second.Error()) \/\/ compare the values, then the texts\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>false true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each <code>errors.New<\/code> call creates a new, unique value. Two errors with the same text are still different errors, which is why sentinels are declared once as package variables.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6. Can you wrap more than one error with fmt.Errorf?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Since Go 1.20, you can use <code>%w<\/code> more than once in the same format string. Then <code>errors.Is<\/code> matches any of the wrapped errors.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ Two separate sentinel errors.\nvar ErrDisk = errors.New(\"disk failed\")\nvar ErrNetwork = errors.New(\"network failed\")\n\nfunc main() {\n    err := fmt.Errorf(\"both: %w and %w\", ErrDisk, ErrNetwork) \/\/ wrap both at once\n    fmt.Println(err)\n    fmt.Println(errors.Is(err, ErrDisk), errors.Is(err, ErrNetwork))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>both: disk failed and network failed\ntrue true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The message joins both texts. Because both were wrapped with <code>%w<\/code>, <code>errors.Is<\/code> finds each of them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Panic and Recover Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7. Where does recover work?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Only inside a deferred function, while a panic is happening. Called anywhere else, <code>recover<\/code> returns nil and does nothing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    fmt.Println(recover()) \/\/ no panic yet, so this prints nil\n\n    defer func() {\n        recovered := recover() \/\/ catches the panic below\n        fmt.Println(\"caught:\", recovered)\n    }()\n\n    var scores map[string]int \/\/ a nil map, never made with make\n    scores[\"asha\"] = 1        \/\/ writing to a nil map panics\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;nil&gt;\ncaught: assignment to entry in nil map<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The first <code>recover<\/code> runs outside a panic, so it returns nil. The deferred one catches the nil map panic.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9. Does a panic in one goroutine get caught by recover in main?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. <code>recover<\/code> only works in the same goroutine that panicked. Each goroutine that might panic needs its own deferred recover, or the whole program crashes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Output Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ CodeError carries an HTTP status code.\ntype CodeError struct{ Code int }\n\n\/\/ Error uses a value receiver.\nfunc (codeError CodeError) Error() string { return fmt.Sprintf(\"code %d\", codeError.Code) }\n\nfunc main() {\n    err := fmt.Errorf(\"api: %w\", CodeError{404})\n    var target CodeError\n    if errors.As(err, &amp;target) { \/\/ &amp;target lets As fill in the value\n        fmt.Println(\"status\", target.Code)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>status 404<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here the custom error uses a value receiver, so we pass a pointer to a <code>CodeError<\/code> variable. <code>errors.As<\/code> needs a pointer to the target so it can fill it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q11. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ check returns an error for negative numbers, with extra context added by defer.\nfunc check(number int) (err error) {\n    defer func() {\n        if err != nil {\n            err = fmt.Errorf(\"check(%d): %w\", number, err) \/\/ add context on the way out\n        }\n    }()\n    if number &lt; 0 {\n        return errors.New(\"negative\")\n    }\n    return nil\n}\n\nfunc main() {\n    fmt.Println(check(5))\n    fmt.Println(check(-1))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;nil&gt;\ncheck(-1): negative<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A deferred function can add context to every error a function returns, using the named <code>err<\/code> result. This keeps each <code>return<\/code> short.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q12. Should you log an error and also return it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Usually no. Doing both causes the same error to appear many times in the logs. Return it with context, and log it once at the top, where you decide what to do.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A money transfer is a classic among Go error handling programs. Write a <code>transfer(from, to *Account, amount int) error<\/code> function that returns a wrapped <code>ErrInsufficientFunds<\/code> sentinel when the balance is too low, and a <code>*ValidationError<\/code> when the amount is zero or negative. In <code>main<\/code>, use <code>errors.Is<\/code> and <code>errors.As<\/code> to print a friendly message for each case. Hint: wrap with <code>%w<\/code> so both checks still work.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pkg.go.dev\/errors\">errors package documentation<\/a><\/li>\n\n\n<li><a href=\"https:\/\/go.dev\/blog\/go1.13-errors\">Working with errors in Go 1.13 (Go blog)<\/a><\/li>\n\n\n<li><a href=\"https:\/\/go.dev\/blog\/defer-panic-and-recover\">Defer, panic and recover (Go blog)<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go error handling programs return <code>error<\/code> as the last result and check it with <code>if err != nil<\/code>.<\/li>\n\n\n<li>Wrap errors with <code>fmt.Errorf<\/code> and <code>%w<\/code> so context is added and the original is kept.<\/li>\n\n\n<li>Use <code>errors.Is<\/code> for specific error values and <code>errors.As<\/code> for error types.<\/li>\n\n\n<li><code>errors.Join<\/code> combines several errors, and <code>%w<\/code> can appear more than once.<\/li>\n\n\n<li>Use panic only for bugs, and recover only inside deferred functions.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we finish Level 4 with dates and times. Read <a href=\"https:\/\/smitabharat.com\/blog\/go-date-time-programs\/\">Go date and time programs with output<\/a>, with formatting, durations, an age calculator and time zones. For more practice, see the <a href=\"https:\/\/smitabharat.com\/blog\/go-error-handling-questions-part-9\/\">Go error handling interview questions<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Go error handling programs show how Go reports and deals with problems, such as a missing file, bad input or a failed payment. Go&hellip;<\/p>\n","protected":false},"author":1,"featured_media":788,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[106],"tags":[96,34,95,11,104],"swapz_series":[],"class_list":["post-809","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-programs","tag-beginner","tag-go-error-handling","tag-go-interview-questions","tag-go-lang","tag-go-programs"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go Error Handling Programs: errors.Is and As<\/title>\n<meta name=\"description\" content=\"Go error handling programs with output: custom errors, wrapping with %w, errors.Is, errors.As, errors.Join, panic and recover, plus interview Q&amp;A.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go Error Handling Programs: errors.Is and As\" \/>\n<meta property=\"og:description\" content=\"Go error handling programs with output: custom errors, wrapping with %w, errors.Is, errors.As, errors.Join, panic and recover, plus interview Q&amp;A.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-08T05:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-28T19:59:31+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"18 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go Error Handling Programs: Wrap, errors.Is, errors.As, Recover\",\"datePublished\":\"2026-10-08T05:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:31+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/\"},\"wordCount\":1954,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-error-handling-programs-featured.png\",\"keywords\":[\"Beginner\",\"Go Error Handling\",\"Go Interview Questions\",\"Go Lang\",\"Go Programs\"],\"articleSection\":[\"Go Programs\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/\",\"name\":\"Go Error Handling Programs: errors.Is and As\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-error-handling-programs-featured.png\",\"datePublished\":\"2026-10-08T05:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:31+00:00\",\"description\":\"Go error handling programs with output: custom errors, wrapping with %w, errors.Is, errors.As, errors.Join, panic and recover, plus interview Q&A.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-error-handling-programs-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-error-handling-programs-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go Error Handling Programs featured image: wrapped errors and recover output\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-error-handling-programs\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go Error Handling Programs: Wrap, errors.Is, errors.As, Recover\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go Error Handling Programs: errors.Is and As","description":"Go error handling programs with output: custom errors, wrapping with %w, errors.Is, errors.As, errors.Join, panic and recover, plus interview Q&A.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/","og_locale":"en_US","og_type":"article","og_title":"Go Error Handling Programs: errors.Is and As","og_description":"Go error handling programs with output: custom errors, wrapping with %w, errors.Is, errors.As, errors.Join, panic and recover, plus interview Q&A.","og_url":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-10-08T05:30:00+00:00","article_modified_time":"2026-11-28T19:59:31+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"18 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go Error Handling Programs: Wrap, errors.Is, errors.As, Recover","datePublished":"2026-10-08T05:30:00+00:00","dateModified":"2026-11-28T19:59:31+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/"},"wordCount":1954,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-featured.png","keywords":["Beginner","Go Error Handling","Go Interview Questions","Go Lang","Go Programs"],"articleSection":["Go Programs"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/","url":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/","name":"Go Error Handling Programs: errors.Is and As","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-featured.png","datePublished":"2026-10-08T05:30:00+00:00","dateModified":"2026-11-28T19:59:31+00:00","description":"Go error handling programs with output: custom errors, wrapping with %w, errors.Is, errors.As, errors.Join, panic and recover, plus interview Q&A.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-error-handling-programs-featured.png","width":2400,"height":1260,"caption":"Go Error Handling Programs featured image: wrapped errors and recover output"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-error-handling-programs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go Error Handling Programs: Wrap, errors.Is, errors.As, Recover"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/809","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=809"}],"version-history":[{"count":1,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/809\/revisions"}],"predecessor-version":[{"id":890,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/809\/revisions\/890"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/788"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=809"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=809"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=809"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=809"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}