From 39cab6087aa26844bb8449871011792bd3ab828c Mon Sep 17 00:00:00 2001 From: Josh Rickmar Date: Wed, 27 May 2015 16:50:05 -0400 Subject: [PATCH] Add waddrmgr.IsError function. --- waddrmgr/error.go | 7 +++++++ waddrmgr/error_test.go | 45 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/waddrmgr/error.go b/waddrmgr/error.go index 2753576..67ed538 100644 --- a/waddrmgr/error.go +++ b/waddrmgr/error.go @@ -204,3 +204,10 @@ func managerError(c ErrorCode, desc string, err error) ManagerError { // Break is a global err used to signal a break from the callback // function by returning an error with the code ErrCallBackBreak var Break = managerError(ErrCallBackBreak, "callback break", nil) + +// IsError returns whether the error is a MangerError with a matching error +// code. +func IsError(err error, code ErrorCode) bool { + e, ok := err.(ManagerError) + return ok && e.ErrorCode == code +} diff --git a/waddrmgr/error_test.go b/waddrmgr/error_test.go index 39143b5..b6e694e 100644 --- a/waddrmgr/error_test.go +++ b/waddrmgr/error_test.go @@ -17,6 +17,7 @@ package waddrmgr_test import ( + "errors" "fmt" "testing" @@ -120,3 +121,47 @@ func TestManagerError(t *testing.T) { } } } + +// TestIsError tests the IsError func. +func TestIsError(t *testing.T) { + tests := []struct { + err error + code waddrmgr.ErrorCode + exp bool + }{ + { + err: waddrmgr.ManagerError{ + ErrorCode: waddrmgr.ErrDatabase, + }, + code: waddrmgr.ErrDatabase, + exp: true, + }, + { + // package should never return *ManagerError + err: &waddrmgr.ManagerError{ + ErrorCode: waddrmgr.ErrDatabase, + }, + code: waddrmgr.ErrDatabase, + exp: false, + }, + { + err: waddrmgr.ManagerError{ + ErrorCode: waddrmgr.ErrCrypto, + }, + code: waddrmgr.ErrDatabase, + exp: false, + }, + { + err: errors.New("not a ManagerError"), + code: waddrmgr.ErrDatabase, + exp: false, + }, + } + + for i, test := range tests { + got := waddrmgr.IsError(test.err, test.code) + if got != test.exp { + t.Errorf("Test %d: got %v expected %v", i, got, test.exp) + } + } +}