how to throw exception that returns 400 HTTP response code |
I have some Codeigniter 4 projects where I extend the base controller with my own base controller. I have a function in this base controller that I call from my various autorouted controller methods if I want to be sure the request is a POST request. Sadly, this results in a 500 error code. I'd like to throw an exception to halt further code execution but I want to return 400 to indicate the error is on the client end. Here's the function in my base controller:
PHP Code: /** From some autorouted controller method, I can use it like so: PHP Code: public function form_handler() { The CI4 docs hint this is possible using HTTPExceptionInterface but don't provide any detail at all about how that might be done. What is considered best practice in this case?
Implement an Exception class that implements HTTPExceptionInterface, and set the error code 400.
And throw it. I think this is not good, but try: PHP Code: throw new class ('BAD REQUEST', 400) extends \Exception implements \CodeIgniter\Exceptions\HTTPExceptionInterface {}; (02-18-2023, 06:40 PM)kenjis Wrote: Implement an Exception class that implements HTTPExceptionInterface, and set the error code 400. Hmmm thank you for the suggestion. That looks pretty clever but doesn't really look ideal. Perhaps I shouldn't be throwing an exception? I like throwing an exception because I get the debug/trace information when environment is "development" and it responds with a generic WOOPS message when environment is "production." Perhaps there's some way to utilize the Response class? It already has statusCodes defined for all the usual HTTP codes. I made my own exception class as you suggested. Sadly, I can't just retrieve the standard phrase for each error code from the Response class because that array, while static, is protected. I sorta borrowed from PageNotFoundException: PHP Code: <?php
Hi, guys,
I'm using exceptions to define a filter that uses IP restriction on my routes. I use this method and I get the file error_403.php : PHP Code: throw new class ('BAD REQUEST', 403) extends \Exception implements \CodeIgniter\Exceptions\HTTPExceptionInterface {}; and if I use : PHP Code: throw new \Exception('BAD REQUEST', 403); I get a 500 header but no 403. |
Welcome Guest, Not a member yet? Register Sign In |