Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Matthew Weier O'Phinney:
Creating Exception types on-the-fly in modern PHP
Dec 07, 2018 @ 17:44:03

Matthew Weier O'Phinney has posted a tutorial to his site sharing a method he's found for creating Exception types dynamically allowing you to create a system that can still be caught by normal means but is more flexible than hard-coded exceptions.

We pioneered a pattern for exception handling for Zend Framework back as we initially began development on version 2 around seven years ago. The pattern looks like this: we would create a marker ExceptionInterface for each package. [Then] we would extend SPL exceptions and implement the package marker interface when doing so.

What this gave users was the ability to catch in three ways. [...] This kind of granularity is really nice to work with. [...] So, what happens when you're writing a one-off implementation of something that is expected to throw an exception matching one of these interfaces?

Why, use an anonymous class, of course!

He includes an example of putting this approach to work, using a throw call along with a dynamic (anonymous) class to extend the required class and implement the associated interface. In his example he creates a dynamic exception for handling a "not found" type of exception.

tagged: exception dynamic tutorial anonymous class custom

Link: https://mwop.net/blog/2018-12-05-on-the-fly-exceptions.html

TheCodingMachine.io:
Safe PHP - Throwing Exceptions Instead of Returning False
Sep 27, 2018 @ 16:47:44

On TheCodingMachine.io there's a tutorial posted by David Négrier covering an interesting idea when handling "falseness" in your PHP application - throwing exceptions rather than returning false. In this case, he introduces the "safe" library to help make this easier.

At TheCodingMachine, we are huge fans of PHPStan. PHPStan is an open-source static analysis tool for your PHP code. [...] PHPStan has this notion of "levels" and we strive on each of our projects to reach "level 7" (the maximum level). But PHPStan is constantly improving, and reaching level 7 becomes harder and harder as the tool becomes more strict (this is a good thing!).

The post includes an example of this increasing strictness, showing how a more recent check looks at a file_get_contents call and ensures all possible return values are evaluated (it returns false when it errors). They refactor the code example to more correctly check for this, but losing some of the "expressiveness". The tutorial then spends some time talking about the history of PHP and why things return false rather than throw exceptions on error. It covers some of the basics of how the safe library works and a PHPStan extension that can help find places that need to be wrapped by "safe" to throw exceptions when false is returned.

tagged: safephp library exception false return value tutorial package

Link: https://thecodingmachine.io/introducing-safe-php

Tomas Votruba:
7 Tips to Write Exceptions Everyone Will Love
Sep 24, 2018 @ 16:55:22

Tomas Votruba has a post to his site sharing his top seven tips for writing exceptions that "everyone will love" and how they could be considered a more than just a programming tool.

Do you ever had that feeling, that you've seen that exception before and you know what it means and how to solve? What if that would be clear even for those who see it for the first time? It would save yours and their time.

Exceptions are not just error state. Exceptions are the new documentation.

He starts off by describing a situation just about any developer would be familiar with, the "circle" where an exception is thrown when something breaks and there's no additional information so you're back to where you started. Based on his work in the EasyCodingStandard he's come up with seven tips to help prevent this in your applications:

  1. Make Exception Names for Humans
  2. Use " around" Statements
  3. What Exactly is Wrong?
  4. What is The Wrong Value?
  5. What File Exactly is Broken?
  6. What Options do I have?
  7. Link what You can't Fit 140 Chars

For each item on the list there's code snippets illustrating the suggestion and a brief description for more context.

tagged: exception suggestion top7 list love tutorial

Link: https://www.tomasvotruba.cz/blog/2018/09/17/7-tips-to-write-exceptions-everyone-will-love/

Laravel News:
PHP 7.3: A Look at JSON Error Handling
Jun 13, 2018 @ 15:18:53

On the Laravel News site there's a tutorial posted looking ahead at PHP 7.3 and some of the changes coming for JSON error handling.

One of the new features coming to PHP 7.3 is better error handling for json_encode() and json_decode(). The RFC was unanimously accepted by a 23 to 0 vote. Let’s take a look at how we handle JSON errors in <= PHP 7.2, and the new improvements coming in PHP 7.3.

They start with an example of how PHP developers would normally check for JSON parsing errors and the typical response when it fails. In the proposed functionality for PHP 7.3 and optional JSON_THROW_ON_ERROR would be added to throw a JsonException if there was an issue parsing the provided data. This also means that you no longer need to manually request the error message, it would just come through as a part of the standard exception. You can find out the full details on the change in the RFC.

tagged: php73 json parse error handling throwable exception feature rfc

Link: https://laravel-news.com/php-7-3-json-error-handling

Sergey Zhuk:
Sending Email Asynchronously With ReactPHP Child Processes
May 04, 2018 @ 14:42:27

Sergey Zhuk has a new tutorial posted on his site showing you how to use child processes in ReactPHP to send emails asynchronously using Swiftmailer.

In PHP the most of libraries and native functions are blocking and thus they block an event-loop. For example, each time we make a database query with PDO, or check a file with file_exists() our asynchronous application is being blocked and waits. Things often become challenging when we want to integrate some synchronous code in an asynchronous application. This problem can be solved in two ways: rewrite a blocking code using a new non-blocking one or fork this blocking code and let it execute in a child process, while the main program continues running asynchronously.

This first approach is not always available, asynchronous PHP ecosystem is still small and not all use-cases have asynchronous implementations. So, in this article, we will cover the second approach.

He starts by creating the main HTTP server handler running locally on port 8080. He adds in an exception handler to catch potential issues and provides example code of an exception being thrown. With that structure in place he starts on the Swiftmailer integration, adding it to the exception handler and pushing the details of the exception into the message body. This is then modified to use the react/child-process package to wrap a new PHP file inside of a child process loop. The tutorial ends with an example of how to pass data between the parent and child process. In this case it's the message from the exception.

tagged: send email child process reactphp tutorial exception asynchronous

Link: http://sergeyzhuk.me/2018/05/04/reactphp-child-processes/

Laravel Daily:
Laravel Exceptions: How to Catch, Handle and Create Your Own
Apr 23, 2018 @ 16:25:10

On the Laravel Daily site they've posted a tutorial showing the Laravel users out there how to create and catch custom exceptions in your application. Exceptions are a useful tool to handle "exceptional situations" where something fails badly enough where the application cannot proceed.

Quite often web-developers don’t care enough about errors. If something goes wrong, you often see default Laravel texts like “Whoops, something went wrong” or, even worse, the exception code, which is not helpful at all to the visitor. So I decided to write a step-by-step article of how to handle errors in elegant way and present proper error information to the visitor.

He uses a "user search" task to help illustrate the methods for creating custom exceptions, catch exceptions and showing the error to the user. Code is included as well as screenshots of the output. With the basics of exception handling out of the way, they move the handling off into a service and take it one step further to create a custom "user not found" exception and its use in the search method.

tagged: laravel exception tutorial handling create catch custom

Link: http://laraveldaily.com/how-to-catch-handle-create-laravel-exceptions/

Matthias Noback:
Exceptions and talking back to the user
Apr 10, 2018 @ 14:13:25

Matthias Noback has a new post to his site with some suggestions about exception handling and user feedback for both the backend experience and UI side.

Designing domain objects is all about offering meaningful behavior and insights through a carefully designed API. [...] So exceptions in your (object-oriented) domain model are not merely meant to signal an exceptional situation. They can be used to prevent invalid or unsupported usage of an object. By offering well-named methods (with sensible parameters) for changing the object's state, and by being very precise about throwing exceptions when invalid use is imminent, you make your domain objects usable in only one way: the way that makes sense. This is the exact opposite of how your domain objects end up looking if you generate getters and setters for every attribute.

He starts by looking at the use of exceptions to help with validation and a few ways they could be used:

  • Exceptions get thrown ad hoc, whenever something threatens the consistency of the domain object.
  • They often signal that something is about to happen that can't logically happen, like a state change that isn't allowed or conceptually possible.
  • Exception messages may contain more information than you'd like to share with the user.
  • Validation errors often require internationalization (i18n).

He explains each option and, where it helps, provides code examples to illustrate. He then moves on to the frontend, talking about changes to the UI when exceptions are thrown and some things on his "wish list" for frontend exception handling.

tagged: exception user messaging handling opinion tutorial

Link: https://matthiasnoback.nl/2018/04/exceptions-and-talking-back-to-the-user/

TutsPlus.com:
Exception Handling in Laravel
Feb 01, 2018 @ 15:37:18

In this new tutorial from the TutsPlus.com site they introduce you to the exception handling that comes along with the Laravel framework and how you can work with it in your own applications.

In this article, we're going to explore one of the most important and least discussed features of the Laravel web framework—exception handling. Laravel comes with a built-in exception handler that allows you to report and render exceptions easily and in a friendly manner.

In the first half of the article, we'll explore the default settings provided by the exception handler. In fact, we'll go through the default Handler class in the first place to understand how Laravel handles exceptions. In the second half of the article, we'll go ahead and see how you could create a custom exception handler that allows you to catch custom exceptions.

You'll need to have a Laravel instance set up already to follow along (instructions not provided here). The tutorial starts with a change to the base configuration for the "APP_DEBUG" and "APP_LOG" settings to enable/disable the error handling and output. Next comes a look at the base exception class for the framework - code included - and a closer look at its report and render methods. Finally it gets into the creation of a custom exception class including the code required to create it and where it should be located in the application for use.

tagged: exception handling laravel tutorial introduction error logging

Link: https://code.tutsplus.com/tutorials/exception-handling-in-laravel--cms-30210

Sebastian De Deyne:
Debugging the dreaded "Class log does not exist" error in Laravel
Oct 26, 2017 @ 14:57:03

Sebastian De Deyne has a post to his site that shares some hints on how to track down the dreaded "class log does not exist" error in Laravel-based applications.

Every now and then I come across a Class log does not exist exception in Laravel. This particular exception is thrown when something goes wrong really early in the application, before the exception handler is instantiated.

Whenever I come across this issue I'm stumped. Mostly it's related to an invalid configuration issue or an early service provider that throws an exception. I always forget how to debug this, so it's time to document my solution for tracking down the underlying error.

As Laravel hides the real issue behind an error thrown from the logging class, it's difficult to determine where the problem actually lies. The path to solve this and get to the actual error involves a change to the handle method and using the die method to output both the message and stack trace of the issue before Laravel can try to handle it. Obviously this is only really meant for debugging but can be handy when this error is hiding the real reason for the failure.

tagged: laravel error message exception logger classlog exist tutorial

Link: https://sebastiandedeyne.com/posts/2017/debugging-the-dreaded-class-log-does-not-exist-error-in-laravel

Paul Jones:
Controllers and Domain Exceptions
May 24, 2017 @ 14:19:52

In a new post to his site Paul Jones shares a conversation he had about handling domain exceptions in controllers and if it was a good practice or not.

A few months ago I had a great email conversation with a correspondent about how to handle business logic exceptions in his controller code. [...] If you find yourself in this situation, the first question to ask yourself is, “Why am I handling domain exceptions in my user interface code?” (Remember: Model-View-Controller and Action-Domain-Responder are user interface patterns; in this case, the user interface is composed of an HTTP request and response.) Domain exceptions should be handled by the domain logic in a domain-appropriate fashion.

He shares the original email (shortened) where they asked their question and outlined their current situation and setup. He points out that the point the other person made about not feeling right to thrown domain exceptions and having the controller handle them is a good path to follow but to take it even further. He suggests modifying the response to the domain logic to be a "domain payload" instead of an exception and then have the controller use that (getting its status) to determine how to proceed. This can prevent the need to catch random exceptions and provides more consistency to the overall flow.

tagged: domain exception controller payload question return tutorial

Link: http://paul-m-jones.com/archives/6608


Trending Topics: