CI4: Handling model errors |
I'm a bit confused on how to properly handle errors that happen in a model:
Exceptions are unrecoverable errors.
To get any database query errors use the below. PHP Code: $error = $db->error(); // Has keys 'code' and 'message' What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
(04-18-2020, 03:26 AM)InsiteFX Wrote: Exceptions are unrecoverable errors. They may be unrecoverable, but through decent exception handling, shouldn't you be able to at least exit gracefully? I've run into a TypeError exception, thrown in CI's BaseModel-file/class, but the exception never bubbles to my own exception handler in the code (which is wrapped around a $mymodel->save() call). Instead the application is terminated and I never receive control back to my (cleanup) code. Hmm ... I just realized TypeError is not actually an exception per se. Re-writing the try {} catch {} block to use \TypeError instead, it actually does get caught and the "exception" handler is invoked. Maybe the documentation should mention this in the "Error Handling" section? -joho (04-17-2020, 03:06 AM)rmilecki Wrote: As CodeIgniter4 seems to mix two ways of handling errors should my controller always do something like: Yes. This is not good design. But if you use Model, you should write code like that. Or change all the errors that the Model returns false to an Exception by yourself. In Shield, we do like that. See https://github.com/codeigniter4/shield/b...nTrait.php
You do know this post is 3 years old.
What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
I do, but it's still valid, no? Or has something changed in CI4 that makes this easier? ?
-joho (08-22-2023, 01:06 AM)kenjis Wrote: @joho See https://www.php.net/manual/en/class.typeerror.php Yes, that's what I wrote in my follow-up post ![]() It makes it hard to write a "catch-all" handler though, when the library/framework code throws different types of errors/exceptions depending on what happens. -joho
You can catch Throwable:
https://www.php.net/manual/en/class.throwable.php (08-22-2023, 01:35 AM)kenjis Wrote: You can catch Throwable: That's great! Maybe something could be put in the CI documentation for this. I consider graceful error handling to be one of the most important aspects of any proper application. -joho |
Welcome Guest, Not a member yet? Register Sign In |