I am trying to raise myExceptions in a service in rails.
But when i rescue with specific name of exception it gives me a nameError for the exception called.
status": 500,
"error": "Internal Server Error",
"exception": "#<NameError: uninitialized constant Api::V1::UsersController::CustomExceptions>",
"traces": {
Exceptions File:
module CustomExceptions
class EmptyObject < StandardError; end
class WrongParams < StandardError; end
class Unauthorized < StandardError; end
end
Exception Raised:
class UsersService
class << self
include AuthenticationHelper
def find_users(current_user, query_params)
users = User.where(some query)
if users.count > 0
users
else
raise CustomExceptions::EmptyObject, "empty user object returned"
end
end
end
end
rescue in controller:
rescue CustomExceptions::EmptyObject => error
render json: {error: 'No users found'}, status: 404
end
Because you define CustomExceptions
, so Rails expect you to define that class in file custom_exceptions.rb
.
In order to call CustomExceptions
, you should rename the filename.