Hi,
I am new to CI and would like to write custom exceptions (extend the PHP Exception class). How do I integrate custom exceptions into CI? Do I need to load the library with $this->load->library(“Exception_document_invalid_id”) in both the class that throws it and the class that traps it? How do I throw and trap it when its loaded (named) like this? I tried a few things but nothing worked. Any help would be most appreciated. Hopefully this can be done. Below is an example of what I am trying to do:
// the extended exception class (not the CI Exception class but the native PHP exception class)
class Exception_document_invalid_id extends Exception {
public function __construct($id) {
....
$code = 101;
$message = "Invalid document ID='" . $id . "'.";
parent::__construct($message, $code);
}
...
}
// the class throwing the custom exception
class Document_model extends Model
{
....
function get_document($id)
{
// test to see if document exists in DB, throw exception if not.
.....
throw new Exception_document_invalid_id($id);
}
....
}
// the class trapping the exception
class Document extends Controller {
....
function view()
{
try
{
.....
$this->load->model('Document_model');
$document = $this->Document_model->get_document($id);
.....
}
catch (Exception_document_invalid_id $ex)
{
$data['error_main'] = get_user_friendly_message($ex->getCode());
log_message('error', "Document:view " . $ex->getMessage(), false);
}
catch (Exception $ex)
{
$data['error_main'] = "Could not retrieve document. Unknown error.";
log_message('error', "Document:view " . $ex->getMessage(), false);
}
}
....
}
Many thanks!
-d