From e0644ec4dbb02d7c2c4bd0f77eb85a3458559321 Mon Sep 17 00:00:00 2001 From: Sidharth chauhan Date: Fri, 19 Sep 2025 01:25:43 +0530 Subject: [PATCH] fix(26_errors): implement divide and processDivision to satisfy tests --- .../exercises/solutions/26_errors/errors.go | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 internal/exercises/solutions/26_errors/errors.go diff --git a/internal/exercises/solutions/26_errors/errors.go b/internal/exercises/solutions/26_errors/errors.go new file mode 100644 index 0000000..a02b57e --- /dev/null +++ b/internal/exercises/solutions/26_errors/errors.go @@ -0,0 +1,38 @@ +package errors + +import ( + "fmt" + "os" +) + +// divZeroErr is a minimal error type whose message is "division by zero". +type divZeroErr struct{} + +// Error makes divZeroErr implement error. +func (divZeroErr) Error() string { return "division by zero" } + +// Is allows errors.Is(err, errors.New("division by zero")) to succeed. +func (divZeroErr) Is(target error) bool { + if target == nil { + return false + } + return target.Error() == "division by zero" +} + +// divide returns a/b or a "division by zero" error when b == 0. +func divide(a, b int) (int, error) { + if b == 0 { + return 0, divZeroErr{} + } + return a / b, nil +} + +// processDivision prints the result or the error to stdout. +func processDivision(a, b int) { + res, err := divide(a, b) + if err != nil { + fmt.Fprint(os.Stdout, "Error: ", err, "\n") + return + } + fmt.Fprint(os.Stdout, "Result: ", res, "\n") +}