Exceptions in Laravel: Why/How to Use and Create Your Own

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys today let's talk about php exceptions in laravel how to use them what are the examples of how other people use that and how to create your own exceptions with your own logic let's start with an example as always i'm a big fan of examples and problem based learning so imagine you have a controller simple controller of showing user by username you find the user and pass that to the view and view is a simple blade based on default laravel 8 page you just show the name show the email show user created at and in the browser it is something like this so user's admin is found and you show name email and create it at now what happens if user is not found for example let's change the url and you get the exception exception comes from the blade because we didn't check actually if the user is found so this object is empty and of course there is an error in a browser and our goal as developers is to show that error correctly in a user-friendly way and the first thing we need to do about it is the security thing to hide that exception in env file here you need to set debug to false locally it may be true but on production server it should show 500 server error so at least hide the actual exception because otherwise you will show a lot of detailed sensitive details about your servers variables and all of that and that is a security issue so that's step one but in reality this is useless 500 server error it doesn't say anything to our visitors to our users and a step in the right direction would be to show a correct error page like 404 not found instead of 500 which is meaningless so to show proper 404 let's change that back to true for now to show proper 404 we can use eloquent method first or fail there is a method find or fail and first or fail and they both in case of failing they will return 404 refresh the page and you see 404 not found and that is better already but still not found what we need to help our visitors to understand what is the error reason so there are two ways how we can customize that 404 page if you just want to make 404 prettier with your own custom design or with more text like that all you need to do is to create a special page let's open the sidebar resources views new directory errors and then if you create blade file with specific error code which is for example 404 blade php and for example this will be a new 404 page save and instead of that not found we refresh it will show the new page for 404 errors similar to 500 or any other errors you just create a blade file with that status code with that error code and it will automatically show when the error with that code appears anywhere in laravel but what if you want to have specific error page for user not found and this is where we get to catching the exception let's get back to our controller and in here instead of first or fail we will do first and then add try catch block so we are trying to get the user if something goes wrong we catch the exception exception and then do something about it in our case let's return another view users not found for example but the main thing here is class name of that exception what can be the exception if you want to catch any exception you just go like this slash exception backslash exception and this one is actually pretty important because there are a lot of classes with the name exception in laravel and in php so there's no guarantee you would not catch some exception from some package or something so backslash exception is php exception so the core of the core exceptions and let's create that user's not found so user's new blade file user not found by username and of course we need to cause that exception to happen because this even if it doesn't return a user it won't cause the exception the exception would be caused by that first or fail so we'll return it back that fail will cause the exception which by default would be handled with 404 page but in our case it would be caught by this statement and we'll show this page let's refresh and there we go user not found by username which means it shows our new page let's get even deeper and catch the right kind of exception the right class of exception because in our case we're catching anything that goes wrong and in any case we're showing user not found and it may be not the case for example if there is some other action in that class for example load some relationship projects which doesn't exist and that would cause totally different exception so let's return that to first then we load the project and we launch the url with existing user the error will be user not found by username although the actual problem is here if we dump if we dump exception get message this is actually the message that comes from the exception the actual error is called to undefined relationship and we need to know the right exception class we can do that by doing get class of that exception like this we refresh relation not found exception so let's do that copy and we need to catch that exception relation not found exception we should return users relations or something some view about relations and in case of this not found let's return that one and catch another exception so the whole thing about exceptions is that you can catch multiple exceptions that come from different parts of your code or some package or some service class and in case of different exceptions you're showing different error messages doing different actions about that so in that case in case of model not found there is a specific class which is model not found exception and actually we can do that same here use this and then we don't need full path here so in case of not found we're showing users not found in case of relations let's do file save as relations blade relation not found by username we refresh the page and now relation not found so if we are doing this then user is not found if we are querying the correct user and loading the relationship wrong then another exception is called and this is what is done shown the actual correct error page a very good example of this catching different exceptions is a stripe library stripe for payment provider see the example of the code of doing any strike request and there are multiple things that may go wrong with credit card with parameters with whatever and for each of them you have a different exception so card exception rate limit exception request exception authentication api connection and stuff like that and the main fallback if there is no exception to be found catch global exception so we now know how to catch the exceptions now let's learn how to throw the exceptions imagine you have some kind of separate class which does all the logic for you and this is a really simple example simplified maybe too much but still you have some kind of service which does finding by username it may be a repository class it may be service class i have a separate video actually about how to use the services and i will link that in the description of this video but anyway you have a service which does find by username which returns the user so it's the same logic we just moved it to some separate class and imagine if some exception happens here how do we catch that in the controller or better question is how do we pass that to controller and this is exactly what throw is about so we are doing user first and then if there's no user like this we do throw new whatever exception we want let's try first model not found exception but not just model not found we can pass a message so user is not found it's not just model it's a user model or not even that by username username like this and then we're doing the catch and we may pass a message error for example exception get message and then inside of that not found we can do just that error that's it of course in reality it would be a pretty design with header and footer and all of that but to simplify i will stick to this example and now if we launch that user admin is okay user admin whatever is exactly the error we've been looking for and it's exactly the error that we passed from our service so we threw the new exception with our message and a step further to that is to create your own exception with your own logic so let's create our own exception class php artisan make exception user not found exception created successfully it is created in app exceptions user not found exception it's empty by default and it extends the default core exception class and then if we look into laravel documentation official documentation there are a few ways how to handle the exception and it actually changed in laravel 8 a bit but i will show you the old logic which still works in laravel 8 with two methods so you have two methods report and render so report and render for report you can log something to somewhere so write something to log file and in render you can return the view whatever you want so user not found and now if we copy that user not found exception into our service instead of default model not found exception we are throwing this actually like this remove that line close the sidebar and we are throwing that user not found and then we need to catch the same exception in the controller not model not found use are not found exception like this and if we refresh the page the result is the same but the benefit of your own exception is more readability so what actually happened of course it's a very simplified example with just a few lines of code but if you have like 50 lines of code and a few services and a lot of things going on the actual exception class with user not found will tell you exactly what happened not just model not found not any http exception or general exception it's user not found exception so your own custom exceptions make the code more readable for other developers and yourself in the future so that's all i wanted to tell you about exceptions in laravel and in php for more information you can read official laravel documentation quite a big page about error handling and if you want to support my channel subscribe to the channel and tell your friends to subscribe because i'm shooting videos almost daily now and also you can support this channel by doing one of two things using our laravel admin panel generator at quickadminpanel.com or enroll in one of my online courses at laraveldaily.teachable.com see you guys in other videos
Info
Channel: Laravel Daily
Views: 45,999
Rating: undefined out of 5
Keywords:
Id: RTTXZVIL6tw
Channel Id: undefined
Length: 12min 17sec (737 seconds)
Published: Mon Sep 28 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.