mailjet / mailjet-gem

[API v3] Mailjet official Ruby GEM
https://dev.mailjet.com
Other
130 stars 72 forks source link

Make full response JSON available to consumers of APIError #195

Open kalleth opened 4 years ago

kalleth commented 4 years ago

Background

Some of the users in my app have invalid email addresses, according to mailjet. This is my bad -- Mailjet evidently uses a different email address validation format to rails (I'm using URI::MailTo::EMAIL_REGEXP). But I wanted to "handle" the error I receive from mailjet, and if the email is reported invalid, mark the user as needing manual intervention to "fix" the problem (or delete the account, etc).

Error handling in Mailjet

The error message I receive from Mailjet contains the following JSON:

{"Messages"=>
  [{"Status"=>"error",
    "Errors"=>
     [{"ErrorIdentifier"=>"d9424b68-9366-46dd-9d59-f7f5fcf113bc", "ErrorCode"=>"mj-0013", "StatusCode"=>400, "ErrorMessage"=>"\"\" is an invalid email address.", "ErrorRelatedTo"=>["To[0].Email"]}]}]}

(produced using Mailjet::Send({'To' => [{'Email' => "" }]}))

This doesn't seem to match the format that ApiError is expecting, and hence self.reason is blank with this error condition.

What I've done here is to make available the fully parsed error message -- for now -- but this is probably the wrong approach.

I think the correct approach is to make ApiError correctly interpret this type of error response, and provide a mailjet_codes (I see that there can be multiple messages, each with multiple errors, so making a single code available also doesn't seem like the right approach).

Until then, by making available the full response object, I can do stuff like this:

  def handle_error(e)
    # we assume (lol) that there's only gonna be a single error message
    error_codes = e.response_json.dig("Messages")&.map do |message|
      message.dig("Errors")&.map do |error|
        error["ErrorCode"]
      end
    end.flatten
    if error_codes.include?("mj-0013")
      raise InvalidEmailError # or other handling logic, like deleting the user/hiding it/etc.
   end
end

Happy to make this better if you give me some pointers on what and where to enhance.