-1

My service authenticate some data on the user's role basis. If the query params are wrong, i want to exit the code and render some error message as the api response?

render json: 'something' and return

Error that i get it:

 "status": 500,
"error": "Internal Server Error",
"exception": "#<NoMethodError: undefined method `render' for AuthenticationService:Class>",
"traces": {
    "Application Trace": [
ashusvirus
  • 412
  • 7
  • 22

1 Answers1

3

The short answer is: you can't.

For something like authentication or permission checking it would be more common to ask your service to authenticate and then that service would either return a value that you can react to or throw an exception that you can react to.

That way each part of your code can take responsibility for what it needs to and no more. Your service can authenticate and your controller can call render.

So, for example, you might end up with something like this in your service:

def authenticate!
  if !okay
    raise AuthenticationError
  end
end

And in your controller:

def my_action
  begin
    AuthenticationService.new.authenticate!
  rescue AuthenticationError
    render json: 'something' and return
  end
end

(This is a very basic example - and I've made up an error class and an okay method to demonstrate)

Shadwell
  • 34,314
  • 14
  • 94
  • 99
  • it gives me a undefined constant error if i write the AuthenticationError after rescue? – ashusvirus Apr 20 '18 at 09:54
  • Yeah, that's because I just made that error class up as an example. You could define your own error class, for example: https://stackoverflow.com/questions/5200842/where-to-define-custom-error-types-in-ruby-and-or-rails – Shadwell Apr 20 '18 at 09:57