0

Is it okay to throw exceptions and errors from not controller or request class in Laravel or in general ?

I have a lot of business logic in my "Repository" class, where I put code to work with data and the database (through Eloquent models). It's kind of an abstraction to avoid cluttering the Eloquent class directly. I am not a master when it comes to building architecture, programming principles, and programming patterns; I'm still learning. So, my question is: Is it okay to throw an exception or error from a method in the Repository or some other Helper class that handles some logic? I don't know where I heard that these kinds of things should only be handled in the controller class. So, I need a piece of advice on this, and thank you for your time!

  • Exception or error handling should not be handled in repository class or service class. So, it is absolutely fine if you take care of these tasks in controller class. – Ali May 27 '23 at 19:23
  • 2
    There is a difference between `throw exception` and `handle exception`, it's two sides of one coin. Of course, you can throw any exception in any class if you think that required by business logic. But handling should be in outer level (if exception in Repository, handle it in Service (or omit and handle in Controller) – lezhni May 27 '23 at 20:39
  • You need to throw an exception when something exceptional happened that you can't handle normally. It does not matter where in the code it happens. – apokryfos May 28 '23 at 06:18
  • @lezhni Thank you for your remark. Can I ask you another question. I have a method in repository and I need to throw ValidationException. Of course I can do this in Controller but it will be much easier and cleaner to throw this exception in repository. I really want to do this in repository class, but I'm trying to become better programmer and write code more correctly. Сan you give me advice on this – Aziz Ismailov May 28 '23 at 08:56
  • @AzizIsmailov can you attach related code to the question? – lezhni May 28 '23 at 14:01
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community May 29 '23 at 04:26

0 Answers0