From 5c663ae710e5ac26e06613b622d2bd9bae3aab20 Mon Sep 17 00:00:00 2001 From: Dai Okumura Date: Fri, 1 Dec 2023 13:29:53 +0900 Subject: [PATCH] Add Custom error class for TypeError --- README.md | 10 +++++----- lib/type_struct/exceptions.rb | 1 + lib/type_struct_test.rb | 11 +++++++---- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 10091db..30f22c6 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ p sample.str #=> "instance of String" sample.string #=> NoMethodError -sample.str = 1 #=> TypeError +sample.str = 1 #=> TypeStruct::TypeError ``` ### Recursive Mapping @@ -184,8 +184,8 @@ Baz = TypeStruct.new( ) p Baz.new(qux: { "a" => [1, 2, 3] }) #=> #[1, 2, 3]}> p Baz.from_hash(qux: { "a" => [1, 2, 3] }) #[1, 2, 3]}> -p Baz.new(qux: { :a => [1, 2, 3] }) #=> TypeError -p Baz.new(qux: { "a" => [1, 2, nil] }) #=> TypeError +p Baz.new(qux: { :a => [1, 2, 3] }) #=> TypeStruct::TypeError +p Baz.new(qux: { "a" => [1, 2, nil] }) #=> TypeStruct::TypeError ``` ### Interface @@ -200,7 +200,7 @@ Foo = TypeStruct.new( # or Interface.new(:read, :write) on required 'type_struct/ext' ) Foo.new(bar: $stdin) -Foo.new(bar: 1) #=> TypeError +Foo.new(bar: 1) #=> TypeStruct::TypeError ``` ### Mix @@ -214,7 +214,7 @@ Baz = TypeStruct.new( p Baz.new(qux: [1]) #=> # p Baz.new(qux: [true, false]) #=> # p Baz.new(qux: nil) #=> # -p Baz.new(qux: 1) #=> TypeError +p Baz.new(qux: 1) #=> TypeStruct::TypeError p Baz.from_hash(qux: [1, 2, false, true]) #=> # ``` diff --git a/lib/type_struct/exceptions.rb b/lib/type_struct/exceptions.rb index ff7b7b7..f240771 100644 --- a/lib/type_struct/exceptions.rb +++ b/lib/type_struct/exceptions.rb @@ -1,5 +1,6 @@ class TypeStruct UnionNotFoundError = Class.new(StandardError) + TypeError = Class.new(::TypeError) class MultiTypeError < StandardError THIS_LIB_REGEXP = %r{lib/type_struct[./]} diff --git a/lib/type_struct_test.rb b/lib/type_struct_test.rb index 6acc253..8dcad1c 100644 --- a/lib/type_struct_test.rb +++ b/lib/type_struct_test.rb @@ -277,8 +277,8 @@ def test_s_from_hash_with_array_of(t) a.from_hash(a: 1, b: 'a') rescue TypeStruct::MultiTypeError => e [ - %r{lib/type_struct_test.rb:#{line}:in TypeError.*?#a expect ArrayOf\(Integer\) got 1}o, - %r{lib/type_struct_test.rb:#{line}:in TypeError.*?#b expect Integer got "a"}o, + %r{lib/type_struct_test.rb:#{line}:in TypeStruct::TypeError.*?#a expect ArrayOf\(Integer\) got 1}o, + %r{lib/type_struct_test.rb:#{line}:in TypeStruct::TypeError.*?#b expect Integer got "a"}o, ].each do |expect| unless expect =~ e.message t.error("message was changed: #{e.message}") @@ -503,9 +503,12 @@ def test_initialize_with_to_hash(t) o = Object.new begin t.new(o) - rescue TypeError + rescue TypeStruct::TypeError => e + unless e.is_a?(::TypeError) + t.error("expect TypeStruct::TypeError is inherit of TypeError") + end else - t.error("expect TypeError") + t.error("expect TypeStruct::TypeError") end def o.to_hash {foo: "a"}