ruby - How do I handle errors or bad requests in my Rails REST API? -


I have a rail app that includes a JSON API interface. When the values ​​are properly specified, the controller handles the happy path properly and JSON is provided as output.

However, if there is a problem with the input, an exception is raised and some templates are saved in instead of rendered "code" Would like to return a JSON error with {"error": {"msg": "bad request", "parameters": ...}} and proper HTTP status codes (such as 403 if they are not authenticated ) But I just want it to request any thing in example.com/api/...//>

Be applicable to How can I do this?

I had a similar case, but I saved different API methods separately because the method Specific errors were needed, I could have saved too many error types on

In my application controller, I had one method:

  Diff error (status, code, message) render: js = & gt; {: Reaction_type = & gt; "Error" ,: response_code = & gt; Code: Message = & gt; Message} .to_json,: position => Position ending  

Then in my API controller

  def some_method ## stuff rescue error (500, method_specific_error_code, "all this has been done") ## Additional error information here if necessary  

Because I save the error, I need to explicitly call on hoptoad api.

To handle the authentication, save before_filter

and 404 to login_required Error for

  def login_required error (403, 403, "not authenticated"):  
  def render_404 error (404, 404, "unknown method") End  

I hope it helps!


Comments

Popular posts from this blog

c# - sqlDecimal to decimal clr stored procedure Unable to cast object of type 'System.Data.SqlTypes.SqlDecimal' to type 'System.IConvertible' -

Calling GetGUIThreadInfo from Outlook VBA -

Obfuscating Python code? -