lorisleiva / laravel-actions

⚡️ Laravel components that take care of one specific task
https://laravelactions.com
MIT License
2.49k stars 121 forks source link

Catching Exceptions in asController method #254

Open AmirVahedix opened 1 year ago

AmirVahedix commented 1 year ago

Hi, Thanks for your great package! Let me explain the problem: I have a phone verification system that sends an OTP code to the user and then verifies it. I handle this in an Action called VerifyUser. It is connected to a route as a controller and also should be responsible for both API and web, so I added htmlResponse and jsonReponse methods.

When an error happens somewhere in my system, like the OTP is not correct, or it is expired, or even the user does not exist, I throw an exception with the message and code. Previously I was handling all this with a try-catch block and returning message as body in API routes, and code as HTTP response code. (and in the web as a flush message) Now all my exceptions are returned as a 500 Server Error. in both API and web.

Is there a way to catch all these exceptions? Wrapping asController and other methods with try-catch didn't worked out. Or I should not throw exceptions for my error messages or validations? I appreciate it if you show me a project source which implemented in the right way.

@lorisleiva Thanks a lot ❤️

lorisleiva commented 1 year ago

Hi Amir, I think it's okay to throw exceptions in your handle method and let them bubble up to whichever ExceptionHandler you are using. I would probably wrap third party exceptions into exceptions that you control though. That way you can even add special traits to them that are going to transform them to HTML or JSON responses. I've not got specific open source projects in mind that I could show you but I'll leave this open and maybe some fellow artisans can share their solutions on tackling third party errors within their code base. ☺️

AmirVahedix commented 1 year ago

Hi Loris, Thanks a lot. The problem is actually that I can't handle my exceptions when I'm using asController method. Using try-catch blocks won't catch them I don't understand how they work