Sunday 15 March 2015

ruby on rails - validation and error-handling for service objects -


I have created a service item in the train to work as an interface between our app and our API.

I got this idea

Here is a small example:

  class packagecceptor def self.get_package (package_id) raise ArgumentError.new (" Package_id can not be zero ") if package_id.blank? Package = API :: get "/ packages / # {package_id}" package = JSON.parse package ,: symbolize_names = & gt; Unless the package.blank happens?   

For assumptions:

  • I have to check all the inputs of zero or wrong type. Is there any way to easy verification? Maybe a rail extension?

    For errors:

    • I can capture all API errors and then return zero to safely. But programmers using the service object may not know the meaning of zero.
    • I can catch API errors and raise another error which means that it is an extra effort to do all the tasks
    • The third option is to leave it and the programmer Handle all the errors from the API.

      Let me know if you know a good pattern or if you have better suggestions for having an API interface.

      . As soon as you start complex cases (many logic, objects, etc.), then I start to tilt.

      Refer to them (see "remove form object"). Sometimes use something like, to build service items. E.g.

        requires 'active_model' to require 'virtus' class CreatePackage includes vertech in ActiveModel :: Validations attribute: name, string attribute: author, string Validates_presence_of: name, : To create the author def, ArgumentError.new ("Invalid Package") does not own unless Valid? Feedback = JSON.parse (API :: Post ("/ packages", auto attributes),: symbolize_names = & gt; true) package. New (answer) end-end class package includes Virtus attribute: id, integer attribute: name, string attribute: author, string and # example Service = CreatePackage.new (: name = & gt; "Tim Toms",: author = & gt; "Tim",) service.valid? # truth; If false, then service.errors package = service.create package.attributes # = & gt; See. {: Id = & gt; 123 ,: Name = & gt; "Tim Tom's",: Author = & gt; "Tim"} As an exception, I leave them for small tasks (like this service class). I'll wrap   if I'm writing something more important, however, a complete API client library.  

      I will never return zero like a network error, or bad or amazing feedback from the server both benefit from the obvious errors.


      Finally, there is a much more complex approach that is called. Even if you do not use it, then there is a bunch of ideas about how to deal with service items, assumptions and results, which you can find interesting.

      Edit : Also, check-out. In addition to simple and less comprehensive, like use_case

No comments:

Post a Comment