Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Best Way to Return Errors from Business Logic or Application?

I am working on an API using Laravel. I am writing business logic and application logic and trying my best to separate them as much as possible. However, I am new in such concepts. For example, I have the logic to log the user in. I have to check:

  1. If the given creds valid or not?
  2. If the creds exist in the system?
  3. If user is active or not
  4. save the data
  5. Try to get some data, but not found
  6. and so on...

I am not checking all this in the controller(as I think it's not the controller's responsibility), but in a separate LoginFormProcessor Class which is delegated by the Controller. If all the checks passes, the LoginFormProcessor will delegate the Object to save/get the object in/from the database. Here is the hierarchy:

Controller -> LoginFormProcessor -> Repository

I want to return the detailed JSON errors (if any) occurred in the LoginFormProcessor or Repository but not directly from these classes (as this is not their responsibility) but from the Controller.

How I can return the mentioned errors to Controller so the Controller could create a meaningful response and sent to the client. Should I return some integer type errorCodes from the LoginFormProcessor and Repository? But then I'll have to check for all the possible error codes, an other headache. I don't think it's a good practice.

Any suggestion and good practices about it?

like image 374
MKJ Avatar asked Oct 29 '22 05:10

MKJ


1 Answers

You want your business logic and your application logic to be agnostic of your delivery mechanism, which mean they should not return HttpCodes. Instead, you should use exceptions (custom exceptions when needed), catch them in your presentation layer (controllers) and transform them accordingly.

As you tagged your question with Laravel, you may have a look at https://laravel.com/docs/5.6/errors#render-method for how to catch the exceptions and translate them to HttpCodes.

like image 55
Phil-R Avatar answered Nov 18 '22 12:11

Phil-R