Laravel: Avoid Try-Catch In Every Method (What To Do Instead)

Поделиться
HTML-код
  • Опубликовано: 12 ноя 2024
  • ХоббиХобби

Комментарии • 29

  • @webdev8659
    @webdev8659 Год назад +7

    With amazing accuracy, Pavillas talks about what I need today. Do you have a crystal ball?
    When will the course "Predictions"? "A personal horoscope for a developer"?

  • @VKLuc
    @VKLuc Год назад +19

    Following is my approach.
    Exceptions are (as their name implies) something that happens exceptionally on the server side. Therefore my approach is to
    1. Use a global exception handler.
    2. Log all the details on the server
    3. Send a meaningful message to the user, explaining what is expected from the user. This should include whether the action may be retried or not and a 'reference id' of the details logged at the server. Never should the message to the user expose the internal workings of the application (such as database errors). Exposing server details is both meaningless and insecure.
    Situations like validations errors on user input should not be handled via exceptions, as they are not exceptional and fit into a normal request/response behavior.
    Br,
    Luc

    • @noisevector
      @noisevector Год назад +1

      Technically Laravel uses a ValidationException for validation errors.

    • @rsgjunior99
      @rsgjunior99 Год назад

      I completely agree with point 1 and 2.
      But I think stating that exceptions should not be used to handle validation errors is too extreme. Your system expects certain parameters, if it doesn't receive, well, that's an exceptional case.
      As Pavillas said, it´s important to create your own types of Exception to be able to diferenciate those cases and not do the same treatment as a default Exception. This can help simplify and centralize error handling.
      In Laravel i don't think it's necessary as you have better ways of doing those validations with the FormRequest classes.

    • @adarshchacko6137
      @adarshchacko6137 Год назад

      @VKLuc How do you go about sending a meaningful message to the user? Do you have a condition inside the global exception handler ?

    • @rsgjunior99
      @rsgjunior99 Год назад

      @@adarshchacko6137 You can have multiple catch blocks catching different types of exception. For example:
      try {
      //code...
      } catch (YourSystemException $e) {
      // send response using $e->getMessage(). This is safe because you know only your system throws this exception.
      // you can do other stuff trough the exception object, like defining a HTTP Status code.
      } catch (Throwable $th) {
      // send response with a generic message
      }

    • @VKLuc
      @VKLuc Год назад

      @@adarshchacko6137 No. Usually I create a custom exception type that is reportable. In its constructor the custom exception type takes the real exception that occurred. In the report and render methods the custom exception type decides what info to send to the logging (report method)and what info to send to the user (render method). It also allocates a reference id for the exception. I often use a uuid that is written to the logging system and shown to the user. (e.g. 'you can contact the helpdesk with reference xxx-xxxx-xxxx)
      The only thing to change in the standard global exception handler is the logic to rethrow each exception as a custom exception.
      public function register(): void
      {
      $this->reportable(function (Throwable $e) {
      throw(new MyCustomException($e));
      });
      }

  • @bbbbburton
    @bbbbburton 10 месяцев назад +2

    The best way to bring your exceptions under control is using @throws annotation with PHPStan (or Larastan if using Laravel). You are then forced to document or handle your exceptions at the right level, or let them bubble up past your controller and to the handler.

  • @stunext
    @stunext Год назад +3

    My approach is to add a render method on my exceptions, so I don't have a huge exception handler. Laravel uses the render method of my exceptions or I use try/catch if needed

  • @tomasfigura4385
    @tomasfigura4385 Год назад +8

    I use try catch so I can put a breakpoint when debugging into the catch part and then I can read error message when error happens.

    • @mauldoto
      @mauldoto 9 месяцев назад

      Yeah, i use try catch to and throw the error with spesific message

  • @SussanRai
    @SussanRai Год назад +2

    Try catch in only controller method but in some cases try catch is used in service layer for certain purpose.

    • @pwcodigo
      @pwcodigo 2 месяца назад

      Que insight. Estou resolvendo esse problema. Eu tenho service e deixa tudo try catch dentro das minhas classes Services. Agora estou passando para controle e alguns casos eu estou colocando usando try catch dentro do service quando me conecto a uma api externa usando macro http do laravel.

  • @NanaYaw
    @NanaYaw Год назад +3

    I use DB transactions in my controller methods and in the catch block, rollback on any kind of exception. What do I do in this case if you advise not to use try catch in controller methods

    • @amitsolanki9363
      @amitsolanki9363 8 месяцев назад +1

      Do you find any solution for this?

  • @devstackdemystified
    @devstackdemystified Год назад +1

    Thanks a lot good stuff big bro!

  • @JamesAutoDude
    @JamesAutoDude 2 месяца назад

    I mostly do try catch when more than one table. If it's just 1 table then I don't bother
    When I do make try catches, I use descriptive errors for each one too

  • @kailasbedarkar7197
    @kailasbedarkar7197 10 месяцев назад

    laravel try catch sometime it has "Exception" OR "Throwable". Is there any difference between them?

    • @JuniorTripod
      @JuniorTripod 9 месяцев назад +2

      Yes, in throwable includes errors, not only exceptions, like TypeError or FatalError. Both exceptions and error implements Throwable interface, so you can catch an error or exception.

  • @someone-jq3lc
    @someone-jq3lc Год назад +1

    what if I want to use DB::transaction() in controller how to combine that with exception handling globally

    • @SXsoft99
      @SXsoft99 7 месяцев назад

      public function update()
      {
      DB::beginTransation();
      try {
      // queries go here
      DB::commit();
      }catch (\Exception $e){
      DB::rollback();
      Log::error($e);
      return error;
      }
      return success;
      }

  • @mahmoud-bakheet
    @mahmoud-bakheet Год назад

    I'm not good in errors handling but i looking my classes where they meet especially when i use services class then i make exception

  • @emekatimothyiloba699
    @emekatimothyiloba699 Год назад +1

    Thanks sir❤

  • @johnnyw525
    @johnnyw525 4 месяца назад

    Exception classes were made for... EXCEPTIONS. Things that your program is not expected to handle! And you're not supposed to misuse exceptions to hide bugs -- you need them to blow up in a big way. It's the whole point of them: If there's a problem with the system, it should be fixed. Not hidden!
    And Exceptions should be LOGGED.
    The user is not expected to deal with them, you, the devs, is! Error codes are for YOU, not the user!

  • @igerardogc
    @igerardogc Год назад

    What theme editor is it? Its very clean and readable, how can i get ur .editorconfig?