Home > Back-end >  Where and how should I handle multiple exceptions?
Where and how should I handle multiple exceptions?

Time:11-25

I have problem with handling exceptions. I know how to do it, but I'm not sure what's the correct place to rescue them. For example:

class ExampleService
  def call
    ...
    raise ExampleServiceError, 'ExampleService message'
  end
end

class SecondExampleService
  def call
    raise SecondExampleServiceError if something

    ExampleService.call
  rescue ExampleService::ExampleServiceError => e ---> should I rescue it here?
    raise SecondExampleServiceError, e.message
  end
end

Class ExampleController
  def update
    SecondExampleService.call
    
  rescue ExampleService::ExampleServiceError, SecondExampleService::SecondExampleServiceError => e
    render json: { error: e.message }
  end
end

As you can see in example I have two Services. ExampleService raises his own exception. SecondExampleService call the ExampleService, can raise exception and is used in ExampleController. Where should I rescue ExampleServiceError? In ExampleController or SecondExampleService? If in ExampleController, what about when we use such a Service in multiple controllers (rescue code will be repeated many times)?

CodePudding user response:

When the controller only calls SecondExampleService directly and doesn't know anything about ExampleService, then it should not rescue from ExampleServiceError.

Only SecondExampleService knows that ExampleService is used internally, and therefore SecondExampleService should rescue from ExampleServiceError and translate it into a SecondExampleServiceError.

That is my interpretation of the law of demeter.

  • Related