| Class | StandardError |
| In: |
maveric/extensions.rb
|
| Parent: | Object |
Extensions to StandardError to enable their usage in Maveric as responses.
| DEFAULT_STATUS | = | 500 |
| DEFAULT_HEADERS | = | {'Content-Type'=>'text/plain'} |
| initialize | -> | old_init |
| body | [W] | |
| headers | [W] | |
| status | [W] |
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#{data.compact.map{|e|e.inspect}*"\n"}" unless data.empty?
86: data = msg
87: end
88: old_init data
89: end