CodeBlanks Logo Icon CodeBlanks

Plugin and error

Learn to handle plugin loading errors.

Plugin errors

Errors come from three places: Open (missing file, version mismatch), Lookup (missing symbol) and the type assertion (wrong type). The single-value form of a type assertion panics; the two-value form is safe:

f, ok := sym.(func(string) string)
if !ok {
    return errors.New("Selam beklenen türde değil")
}

Wrapping errors

Wrap errors with context to see which plugin and which step failed:

p, err := plugin.Open(yol)
if err != nil {
    return fmt.Errorf("plugin %s açılamadı: %w", yol, err)
}

%w keeps the original error, which can still be queried with errors.Is.

Practice Write a safe assertion

Declare var sym any = 42. Assert with f, ok := sym.(func() string); if ok is false print fmt.Println("tür uyumsuz").

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    var sym any = 42
    f, ok := sym.(func() string)
    if !ok {
        fmt.Println("tür uyumsuz")
        return
    }
    fmt.Println(f())
}

Expected output

tür uyumsuz

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>f := sym.(func())</code> do if the assertion fails?

  • It returns false
  • It fails to compile
  • It panics Correct answer
  • f becomes nil

Explanation: A single-value type assertion panics on mismatch; the ", ok" form gives ok=false instead.

2 Safe assertion

Question
f, ____ := sym.(func() string)
if !ok { return }
Answer
f, ok := sym.(func() string)
if !ok { return }

Explanation: In a two-value type assertion the second value is a bool reporting success.

3 Error source

Term Meaning
Missing file plugin.Open
Missing symbol Lookup
Wrong type Type assertion
Adding context fmt.Errorf and %w

All lessons in Advanced