Middle
How to make the library consumer obliged to handle a custom exception?
sobes.tech AI
Answer from AI
To make a library consumer handle a custom exception, several approaches can be used:
-
Declare the exception in the function signature (if the language supports checked exceptions, e.g., Java). In Go, exceptions are not used, but errors of a specific type can be returned.
-
In Go: define a custom error type that implements the
errorinterface, and document that the function may return this specific error type. The consumer must check the error type to handle it correctly.
Example in Go:
package mylib
import "fmt"
type MyCustomError struct {
Msg string
}
func (e *MyCustomError) Error() string {
return e.Msg
}
func DoSomething() error {
// ... some logic
return &MyCustomError{Msg: "something went wrong"}
}
Consumer:
err := mylib.DoSomething()
if err != nil {
if customErr, ok := err.(*mylib.MyCustomError); ok {
// Handle custom error
fmt.Println("Handled custom error:", customErr)
} else {
// General error handling
}
}
Thus, the consumer must explicitly check and handle the custom exception.