In this episode, we start exploring custom exception handling in our app. The main goal is to set things up so we can display a custom 404 page (or another error page) whenever something goes wrong, instead of just seeing a generic error message or stack trace.
We first look at how errors are currently handled—if we hit a route that doesn't exist, we get a default 'not found' exception. That's fine for debugging, but for production we want something much friendlier for users, like a tailored 404 page.
To make this happen, we head back to our App
class and start organizing our error handling. Rather than crowding the main app file, we create a separate class called ExceptionHandler
inside a new Exceptions directory. This new handler is hooked up to our container, so we can easily grab it where needed.
The plan is that whenever an error comes up, our app will send the error (along with the request and response objects) to this ExceptionHandler. For now, it just passes things along like before, but the structure is there so we'll easily be able to modify the response—like rendering a custom error page—in future episodes.
This sets us up nicely for the next step: actually rendering a custom view when an exception occurs. Stay tuned for that in the next episode!