Japs
Japs

Reputation: 1

Is there a way using GRAPE to trap all exceptions within the API instead of showing HTML error page

We are using Grape to provide a API; the API raises exceptions in a lot of places randomly because of insufficient parameters, nils etc. This causes Rails to produce an HTML error page. Is there a way to control this and wrap all calls to return an error message instead?

We are using

API

gem 'grape', '0.9'
gem 'grape-swagger', '0.8.0'
gem 'grape-swagger-rails'

For example: if any error occurs in the API, it does not reach

rescue ArgumentError => ex
    error! ex.message
rescue Mongoid::Errors::Validations => ex
    error! ex.message

of the API method. We need a way to catch exact error message bypassing the HTML error page.

Already tried this

https://code.dblock.org/2011/05/04/grape-trapping-all-exceptions-within-the-api.html

not sure where to inject the ApiErrorHandler .

Expected results should be "result: xyz error message"

Upvotes: 0

Views: 352

Answers (2)

MikeWu
MikeWu

Reputation: 3732

I'm not sure if this will work with your setup, but Grape has built in way of doing this kind of thing. From the documentation:

class Twitter::API < Grape::API
  rescue_from ArgumentError do |e|
    Rack::Response.new([ "ArgumentError: #{e.message}" ], 500).finish
  end
  rescue_from NotImplementedError do |e|
    Rack::Response.new([ "NotImplementedError: #{e.message}" ], 500).finish
  end
end

Upvotes: 0

Martin
Martin

Reputation: 4222

not sure where to inject the ApiErrorHandler

In your Grape controller:

require 'api_error_handler'

class Api_v1 < Grape::API
  prefix 'api'
  version 'v1'

  use ApiErrorHandler

  ...
end

Code example from an article you linked


Or you can catch exceptions in helper method. Something like:

module ActionsHelper
  extend Grape::API::Helpers

  def request_with_error_handling(options = { status: 422 }, &block)
    raise ArgumentError, 'Options are nil' if options.nil?
    raise ArgumentError, 'No block given' unless block_given?

    yield

    rescue Mongoid::Errors::Validations => ex
      error! ex.message
    rescue ArgumentError => ex
      error! ex.message
  end
end

# users as an example
class Users < Grape::API
  namespace :users do
    helpers ActionsHelper

    desc 'Create new user'
    params do
      # user params
    end
    post '/' do
      request_with_error_handling do
        # your user creation logic here
        # any exception would be catched 
        # in request_with_error_handling helper method
      end
    end
  end
end

Upvotes: 1

Related Questions