How to return custom error codes in a Rails API? - ruby-on-rails

Given a RESTful API, implemented in Rails, I want to include in the responses not only the errors messages, generated by ActiveModel::Validations, but also custom error codes. First of all I would like to point out that I am not talking about HTTP Status codes. I am talking about having an error of any type (from general errors like record not found to small validation errors like username can't be blank) be mapped to a unique numeric code, that is custom application-specific error codes. Let me give an example - given a list of error codes, like:
1: record not found
... some other errors
# Validation errors for User model between 1000 to 2000
1001: first name can't be blank
1002: first name must contain at least 3 characters
1003: last name can't be blank
1004: last name must contain at least 3 characters
...some other errors
If I have a form for a user and submit it with empty fields for first and last name, I want to have in the response body something like:
{error_codes: [1001, 1002, 1003, 1004]}
or something similar (for example I could have an array of error objects, each with a code, message for developer, message for user etc.). Let me give an example with the Twilio API, taken from RESTful API Design: what about errors?:
Here, 20003 is some custom Twilio-specific code. The question is - how can this be implemented in Rails? I see several difficult aspects:
how do I get a list of all possible errors that can be encountered. It is hard to get such a list even only for the validation errors, let alone the other types of errors that can occur.
how should this list be organized - maybe in a YAML file?
how do I access the list - maybe something similar to the way translations are accessed via I18n.t?
I will really appreciate any advice on the topic. Thank you.
P.S. I think this is a similar question.

ActiveModel built-in validators can be found here. Sometimes one validator can check for more than one thing and output different messages. The easiest way to see them all is, as you've guessed, in its I18n yaml file, which can be found here.
One way of doing what you want is overwriting those messages with your custom codes. Another way is passing a custom message when explicitly attaching a validator to your models.
validates :name, message: 'code:001 - my custom message'
Those two options won't help you with structure, though. You won't have a different key code on your json out of the box.
One way you can accomplish that is to can create a helper to parse the error messages and extract the codes after they have been assigned to a model instance. Something along the lines of:
def extract_error_codes(error_messages)
error_messages.map{ |message| message.match('^code:(\d+)\s-')[1] }
end
That would give you an array of error codes for that instance if you'd used the format code:001 - my custom message.
Another, much more involved way, is to tap into ActiveModel's Validator class and store an error code when a validation fails. That would require going into each validator to assign the code.

Related

How to add extra components to HL7 message using Java Hapi?

I am working on building a replacement to MIRTH and it looks like we are sending out non-standard HL7 ORU_R01 messages. OBR.5 should be just a single field but looks like we are sending a bunch of other data in this section.
<OBR.5>
<OBR.5.1>XXXX</OBR.5.1>
<OBR.5.2>XXXX</OBR.5.2>
<OBR.5.3>XXXXX</OBR.5.3>
<OBR.5.5>XXXXX</OBR.5.5>
<OBR.5.6>XXXX</OBR.5.6>
<OBR.5.7/>
<OBR.5.8>XXXXXXXXXX</OBR.5.8>
<OBR.5.10>XXXXXXX</OBR.5.10>
<OBR.5.11>X</OBR.5.11>
<OBR.5.12>X</OBR.5.12>
<OBR.5.13>XXXXX</OBR.5.13>
<OBR.5.15>XXXXXXX</OBR.5.15>
</OBR.5>
It seems like I should be able to something like the following.
obr.getObr5_Priority().getExtraComponents().getComponent(2).setData(...)
But I am having issues trying to find the correct way to set the different segments. All the fields are Strings.
Found something that I think has ended up working for us.
ID expirationDate = new ID(obr.getMessage(), 502);
expirationDate.setValue(format2.format(date));
obr.getObr5_Priority().getExtraComponents().getComponent(0).setData(expirationDate);
Where 503 refers to which element you want to set. In this case I am trying to set OBR-5.2. getComponent(0) because it's the first extra component I am adding for this particular segment. I am not sure entirely if my explanation here is correct but it creates a message we need and parses as I'd expect so its my best guess.
Dereived the answer from this old email thread https://sourceforge.net/p/hl7api/mailman/hl7api-devel/thread/0C32A03544668145A925DD2C339F2BED017924D8%40FFX-INF-EX-V1.cgifederal.com/#msg19632481

How to validate multiple fields together?

I could not find anything in the doc or issues except for form-level validation not being possible.
I have several fields that I need to validate together and return 1 error message. When I return an error value from resolver for something that is not a field, then then errors does not contain it.
Is it possible to achieve something like this with the library? If not, can you suggest a hook library that can?

Quickfixj not honoring custom fields in a repeating group

I am using FIXT1.1 and FIX Application version 5.0SP2.
I added some custom fields to the QuotSetAckGrp, part of MassQuoteAcknowledgement message. However, when quickfix reads the repeating group, it does not read the custom fields as part of the repeating groups. Instead, it treats the custom fields are regular parent-level fields and throws a "Tag appears more than once" session level reject.
Appreciate any inputs to help resolve the issue.
You need to modify the receiver's AppDataDictionary to match the messages that your sender is sending. Also, you need to set UseDataDictionary=Y in your config.
QF/j needs to look at the DD xml file to know what fields are in a repeating group, else it cannot know where each group member ends.
When the engine encounters a field that isn't inside the DD's repeating group definition, it assumes that the current group member ended with the previous tag.
Here's a howto for customizing your DD:
http://quickfixn.org/tutorial/custom-fields-groups-and-messages
(The above link is for QF/n, but it's nearly the same for QF/j.)
See the QuickFIX/J User FAQ, topic "I altered my data dictionary. Should I regenerate/rebuild QF/J?".
OUTGOING MSGS: The DD xml file is irrelevant when you construct
outgoing messages. You can pretty much add whatever fields you want to
messages using the generic field setters (setString, setInt, etc) and
QF will let you. The only trouble is with repeating groups. QF will
write repeating group element ordering according to the DD that was
used for code generation. If you altered any groups that are part of
outgoing messages, you DEFINITELY need to rebuild.
To rebuild QuickFIX/J to accept your custom data dictionary, please refer to the answer I gave in the following StackOverflow post.
HTH.

How do i filter and validate form fields in symfony 1.4?

Im trying to integrate a content filtering API. My plan was to use pre/post validators but I've lost may way somehow.
What i need to do is send the values to the content filtering service. If the response comes back that the content has been filtered it will also return a modified value for the field (basic profanity filtering... matches are replace with asterisks). Thats all well and good i can throw validation errors no problem - simple stuff.
However i dont want just throw errors. What needs to happen is that validation errors are thrown as normal, but the values are modified in the form for re-display.
Basically if someone posts something naughty i want them to get a validation error saying their post has been modified, they can re-submit the now "clean" post, or they can go about editing it to make it clean without the word replacements.
But do clean on a validator either throws an error OR returns cleaned values, not both. How can i go about implementing both? This will be used on many different forms with many different field names, so modifying methods on the form or a form base class isnt really an option - it needs to happen in the validation sub-framework somehow.
You can adjust this plugin for your needs http://www.symfony-project.org/plugins/WebPurifyPlugin

Omit attribute name from validation error message (at start of it)?

I write code in English but I'm currently doing a site which is fully translated to another language (validation error messages included). However, I have a problem because validation error messages always seem to include the name of the attribute the error is on at the start of the error, e.g.:
Title Prosimo izpolnite naziv fakultete.
I want to get rid of the Title at the start, like so:
Prosimo izpolnite naziv fakultete.
Any help is appreciated. I would rather see if this can be solved without installing any 3rd party plugins.
If it's possible to provide translations for attribute names, that would be a cool solution too, but I would still like to know how it can be done both ways (omit or translate).
There is no need to use the error_messages_for helper for errors, you can write your own helper using the record's errors attribute.
You can just iterate over the error objects and display their messages.

Resources