Sha256: a9e2d117ce50d2682dc05b007712628bee836c031087c6602ddf2db695ad6682

Contents?: true

Size: 1.62 KB

Versions: 17

Compression:

Stored size: 1.62 KB

Contents

module Startback
  module Web
    #
    # This Rack middleware catches all known exceptions raised by sublayers
    # in the Rack chain. Those exceptions are converted to proper HTTP error
    # codes and friendly error messages encoded in json.
    #
    # Please check the Errors module about status codes used for each Startback
    # error.
    #
    # This class aims at being used as top level of a Rack chain.
    #
    # Examples:
    #
    #     Rack::Builder.new do
    #       use Startback::Web::Shield
    #     end
    #
    class Shield < Rack::Robustness
      include Errors

      self.no_catch_all
      self.content_type 'application/json'

      # Decoding errors from json and csv are considered user's fault
      self.on(Finitio::TypeError){ 400 }
      self.on(::NotImplementedError){ 501 }

      # Various other codes for the framework specific error classes
      self.on(Startback::Errors::Error) {|ex|
        ex.class.status
      }

      # A bit of logic to choose the best error message for the user
      # according to the error class
      self.body{|ex|
        body_for(ex).to_json
      }

      def body_for(ex)
        ex = ex.root_cause if ex.is_a?(Finitio::TypeError)
        body = { code: ex.class.name, description: ex.message }
        return body unless ex.is_a?(Startback::Errors::Error)
        return body unless ex.has_causes?

        body[:causes] = ex.causes
          .filter{|cause|
            cause.is_a?(Startback::Errors::Error)
          }
          .map{|cause|
            body_for(cause)
          }
        body
      end

    end # class Shield
  end # module Web
end # module Startback

Version data entries

17 entries across 17 versions & 3 rubygems

Version Path
startback-0.14.4 lib/startback/web/shield.rb
startback-0.14.3 lib/startback/web/shield.rb
startback-0.14.2 lib/startback/web/shield.rb
startback-0.14.1 lib/startback/web/shield.rb
startback-0.14.0 lib/startback/web/shield.rb
startback-jobs-0.14.0 lib/startback/web/shield.rb
startback-websocket-0.14.0 lib/startback/web/shield.rb
startback-0.13.0 lib/startback/web/shield.rb
startback-0.12.3 lib/startback/web/shield.rb
startback-0.12.2 lib/startback/web/shield.rb
startback-0.12.1 lib/startback/web/shield.rb
startback-0.12.0 lib/startback/web/shield.rb
startback-0.11.5 lib/startback/web/shield.rb
startback-0.11.4 lib/startback/web/shield.rb
startback-0.11.3 lib/startback/web/shield.rb
startback-0.11.0 lib/startback/web/shield.rb
startback-0.10.1 lib/startback/web/shield.rb