All posts

Rails error handling cheatsheet

A few notes to refer to for Rails JSON api error handling in controller actions:

*This is not a comprehensive post. It is a quick reference if you have some experience with Rails but haven’t used it recently.

  1. To raise an error on a query that does not find a record use the bang operator (!) on the end of the query method:
    # if this query returns empty no error is raised
# if this query returns empty an error is raised
  1. The create and update methods will through some errors without the ! operator, like a SQL NOT NULL constraint violation. However it will not throw app validation errors. The errors will still be available as data on the object but the app will not crash. If you add the ! to create or update then if a validation error occurs an error will be raised.
# does not raise app validation errors
store = Store.create(store_params)

if store.errors
  render json: {errors: app.errors.full_messages}
# does raise app validation errors

rescue => e
  render json: {errors: [e.message]}
  1. If want to render a JSON error message instead of a Rails error page, a couple options are to explicitly raise the error you want or rescue the error and handle the JSON formatting for the error:
store = Store.from_external_id(params["external_id"])

if store
  render json: {success: store}
  render json: {error: {message: "Store not found"}}


store = Store.from_org_external_id!(params["external_id"])

rescue => ActiveRecord::RecordNotFound
  render json: {error: {message: "Store not found"}}

Resources I found useful when writing this: