Jordon Bedwell wrote in post #1087053:
> On Thu, Nov 29, 2012 at 3:47 AM, comopasta Gr <[email protected]>
> wrote:
>> error_type = Struct.new(:code, :description)
>> BAD_JSON = error_type.new("001" , "Problem parsing JSON")
>> BAD_XML = error_type.new("002" , "Problem parsing XML")
>
> class MyClass
>   class APIParseError < StandardError
>     def initialize(code, lib)
>       @code = code
>       @lib = lib
>     end
>
>     def to_s
>       "#{@code}: Problem parsing #{@lib}"
>     end
>   end
> end
>
> raise(MyClass::APIParseError.new("001", :XML))
> #=> MyClass::MyError: 001: Problem parsing XML

Thanks Jordon. I wanted to keep my question simple but maybe it needed
more details. Sorry I have to paste a bunch of code...

I need to respond with the api using json:

{
  "result": {"created":"0","failed":"0"},
  "errors":[
    {"error":{"message":"Problem parsing JSON","code":"001"}}
  ]
}

I use Rabl to generate the json I give back. Rabl works well with
openStruct. There can be several errors to be reported.

--------

The controller delegates to a module this and other validations on the
json.

Relevant code from the controller:

@result = OpenStruct.new
@errors = []

entries = ApiUtilitiesV1::validateJson(request.body.read)
if entries != false
  ..keep processing, might add elements to the @errors array
else
  err = ApiUtilitiesV1::getError(BAD_JSON)
  @errors << err
end

@result.created = "#{created_counter}"
@result.failed = "#{failed_counter}"
render 'create' -> renders Rabl template using @result and @errors

-------

In the module where I have the api utilities there is:

def self.validateJson(json_string)
  begin
    parsed_vals = JSON.parse(json_string)
    return parsed_vals["entries"]
  rescue JSON::ParserError
    return false
  end
end

def self.getError(error_constant)
  error = OpenStruct.new
  error.message = error_constant.message
  error.code = error_constant.code
  return error
end

--------

The idea is to share the error codes defined in the structs between the
controller and the module. And also have a single method that provides
me with the data that goes in for each different error.

So I'm not sure how can I incorporate your suggestion into the logic I 
have. Or maybe the logic I have is completely a bad idea...

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to