![]() ![]() These provide a generalized classification and having your own exceptions extend these makes it easier for consuming code to catch them. The Standard PHP Library (SPL) provides a predefined set of exceptions that I would recommend you to build upon. If the connection could not be established, however, we might want to have our exception bubble up to the infrastructure layer to immediately point to a bigger issue. This will let a user continue working with the system without getting fatal errors. Did the database not return a result because that ID was not known? Maybe return a NullObject instead of throwing an error. This allows you to catch and gracefully handle exceptions directly in the calling code when this makes sense, and let them bubble to the surface if not.Īs an example, when your code that fetches an entry from the database throws an exception, you can handle this in a nuanced way based on the type of the exception. And, as they escalate throughout your different layers of code, you can decide for each exception at which layer and in which context you want to deal with them. The error handler is somewhat outside of the context of you current execution flow, so it is very difficult to do anything meaningful to recover from the error once you’ve reached that point.Įxceptions, on the other hand, can be dealt with at any point in your code. ![]() Apart from being able to set different error handlers for different levels of errors, you have no further way of controlling the point where you can deal with your errors. Normal PHP errors and warnings come from the procedural world, and they provide one central mechanism to deal with these errors, a function you declare as being the error handler through the set_error_handler method. Why Even Use Exceptions?īefore discussing implementation details, I think it is necessary to mention what the main benefit of exceptions is when compared to something like trigger_error. In this article, I want to talk about the way I currently set them up and use them in PHP, in the hopes to spark some discussion on the topic and get further feedback. Your client will surely be thankful! In large #PHP projects, start with a proper structure to avoid expensive refactoring later on. The larger and more complex your projects become, the more important it is to start with a proper structure to avoid expensive refactoring later on. While the consensus is to use exceptions, there is very little information on how to structure and manage them in a larger codebase. I think it is an area that I haven’t yet fully explored, and it is very difficult to find anything more than very basic explanations and tutorials online. I seem to constantly work on improving my habits regarding the use of exceptions.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |