lib/nanoc/cli/error_handler.rb in nanoc-4.8.16 vs lib/nanoc/cli/error_handler.rb in nanoc-4.8.17

- old
+ new

@@ -56,16 +56,24 @@ # Run yield rescue Interrupt exit(1) rescue StandardError, ScriptError => e - if trivial?(e) - $stderr.puts "Error: #{e.message}" - resolution = resolution_for(e) - $stderr.puts resolution if resolution + handle_error(e, exit_on_error: exit_on_error) + end + + def handle_error(error, exit_on_error:) + if trivial?(error) + $stderr.puts + $stderr.puts "Error: #{error.message}" + resolution = resolution_for(error) + if resolution + $stderr.puts + $stderr.puts resolution + end else - print_error(e) + print_error(error) end exit(1) if exit_on_error end # Prints the given error to stderr. Includes message, possible resolution @@ -146,10 +154,22 @@ ruby_2_5_used = ruby_version.start_with?('2.5') feature_enabled || ruby_2_5_used end + # @api private + def trivial?(error) + case error + when Nanoc::Int::Errors::GenericTrivial, Errno::EADDRINUSE + true + when LoadError + GEM_NAMES.keys.include?(gem_name_from_load_error(error)) + else + false + end + end + protected # @return [Hash<String, Array>] A hash containing the gem names as keys and gem versions as value def gems_and_versions gems = {} @@ -194,19 +214,10 @@ 'rubypants' => 'rubypants', 'sass' => 'sass', 'w3c_validators' => 'w3c_validators', }.freeze - def trivial?(error) - case error - when Nanoc::Int::Errors::GenericTrivial, Errno::EADDRINUSE - true - else - false - end - end - # Attempts to find a resolution for the given error, or nil if no # resolution can be automatically obtained. # # @param [Error] error The error to find a resolution for # @@ -214,19 +225,19 @@ def resolution_for(error) error = unwrap_error(error) case error when LoadError - # Get gem name - matches = error.message.match(/(no such file to load|cannot load such file) -- ([^\s]+)/) - return nil if matches.nil? - gem_name = GEM_NAMES[matches[2]] + gem_name = gem_name_from_load_error(error) - # Build message if gem_name if using_bundler? - 'Make sure the gem is added to Gemfile and run `bundle install`.' + <<~RES + 1. Add `gem '#{gem_name}'` to your Gemfile + 2. Run `bundle install` + 3. Re-run this command + RES else "Install the '#{gem_name}' gem using `gem install #{gem_name}`." end end when RuntimeError @@ -237,9 +248,15 @@ end when Errno::EADDRINUSE 'There already is a server running. Either shut down that one, or ' \ 'specify a different port to run this server on.' end + end + + def gem_name_from_load_error(error) + matches = error.message.match(/(no such file to load|cannot load such file) -- ([^\s]+)/) + return nil if matches.nil? + GEM_NAMES[matches[2]] end def using_bundler? defined?(Bundler) && Bundler::SharedHelpers.in_bundle? end