Class StandardError
In: maveric/extensions.rb
Parent: Object

Extensions to StandardError to enable their usage in Maveric as responses.


body   headers   new   status   to_http  


DEFAULT_HEADERS = {'Content-Type'=>'text/plain'}

External Aliases

initialize -> old_init


body  [W] 
headers  [W] 
status  [W] 

Public Class methods

After a bit of experimenting with Exception and raise I determinee a fun and simple way to generate fast HTTP response error thingies. As long as you‘re within a call to dispatch (with no further rescue clauses) the StandardError will propogate up and be returned. As a StandardError has similar accessors as a Controller, they should be compatible with any outputting implimentation.

  raise StandardErrpr; # 500 error
  raise StandardError, 'Crap!'; # 500 error with message set to 'Crap!'
  raise StandardError, [status, headers, body, *other_data] # Magic!

In the final example line an Array is passed to raise as a second argument rather than a String. This is taken as the HTTP status code. The next element is tested to be a Hash, if so then it‘s values are merged into the HTTP headers. Then next item is tested to be a String, if so it is appended to the response body. All remaining elements are appended to the response body in inspect format.

A simple way of only including data that might be interpreted to being the status, headers, or body is to place a nil previous to the data you want apended to the response body.


    # File maveric/extensions.rb, line 77
77:   def initialize data=nil
78:     #consider autosettign @status, like 503 for NoMethodError
79:     if data.is_a? Array and data[0].is_a? Integer
80:       @body = ''
81:       @status = data.shift if Integer === data.first
82:       @headers = DEF_HEADERS.merge data.shift if Hash === data.first
83:       @body << data.shift if String === data.first
84:       msg = @body.dup
85:       @body << "\n\n#{{|e|e.inspect}*"\n"}" unless data.empty?
86:       data = msg
87:     end
88:     old_init data
89:   end

Public Instance methods

Unless @body is defined, a self inspect and backtrace is output.


    # File maveric/extensions.rb, line 47
47:   def body; @body or [inspect, *backtrace]*"\n"; end


    # File maveric/extensions.rb, line 45
45:   def headers; @headers or DEFAULT_HEADERS; end


    # File maveric/extensions.rb, line 44
44:   def status; @status or DEFAULT_STATUS; end

See ::Maveric::Controller#to_http


    # File maveric/extensions.rb, line 49
49:   def to_http
50:     response = "Status: #{status}"+::Maveric::EOL
51:     response <<{|(k,v)| "#{k}: #{v}" }*::Maveric::EOL
52:     response << ::Maveric::EOL*2 + body
53:   end