From 71b97b6a382f11271d21acc94587b1e3e1168723 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Thu, 27 May 2021 08:59:53 +0900 Subject: [PATCH] add runtime error --- src/mechanize.cr | 1 + src/mechanize/errors/base_error.cr | 3 +++ src/mechanize/errors/element_not_found_error.cr | 13 +++++++++++++ src/mechanize/form.cr | 6 ++++-- 4 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 src/mechanize/errors/base_error.cr create mode 100644 src/mechanize/errors/element_not_found_error.cr diff --git a/src/mechanize.cr b/src/mechanize.cr index dd4a30c..d1a8cd6 100644 --- a/src/mechanize.cr +++ b/src/mechanize.cr @@ -2,6 +2,7 @@ require "./mechanize/http/agent" require "./mechanize/form" require "./mechanize/node" require "./mechanize/page" +require "./mechanize/errors/*" class Mechanize VERSION = "0.1.0" diff --git a/src/mechanize/errors/base_error.cr b/src/mechanize/errors/base_error.cr new file mode 100644 index 0000000..67be8ce --- /dev/null +++ b/src/mechanize/errors/base_error.cr @@ -0,0 +1,3 @@ +# Base Error class +class MechanizeCr::Error < RuntimeError +end diff --git a/src/mechanize/errors/element_not_found_error.cr b/src/mechanize/errors/element_not_found_error.cr new file mode 100644 index 0000000..8d134b4 --- /dev/null +++ b/src/mechanize/errors/element_not_found_error.cr @@ -0,0 +1,13 @@ +require "./base_error" +class MechanizeCr::ElementNotFoundError < MechanizeCr::Error + getter element : Symbol + getter conditions : String + + def initialize(element, conditions) + @element = element + @conditions = conditions + + super "Element #{element} with conditions #{conditions} was not found" + end + +end diff --git a/src/mechanize/form.cr b/src/mechanize/form.cr index bd685a2..4034a9a 100644 --- a/src/mechanize/form.cr +++ b/src/mechanize/form.cr @@ -72,15 +72,17 @@ class MechanizeCr::Form # TODO # when args whose type isn't String is given end - fields.select do |field| + f = fields.select do |field| value.all? do |k,v| v === field.name end end + f.empty? ? nil : f end def field_with(criteria) f = fields_with(criteria) - f.empty? ? Array(MechanizeCr::FormContent::Field).new : f.first + raise MechanizeCr::ElementNotFoundError.new(:field, criteria) if f.nil? + f.first end end