Welcome Guest, Not a member yet? Register   Sign In
Custom Error function - Extend Exceptions or add to Common? Confused
#1

[eluser]the real rlee[/eluser]
Hi guys, I would like to add a new error function which i can call anywhere in my CI app much like show_error(). I've read some posts about extending the Exceptions library, but it seems show_error() is a wrapper for the Exceptions show_error() function so I'm assuming the only way to create a custom error function which i can call just like show_error() is to ad it directly the Common.php file (?)
#2

[eluser]Glen Swinfield[/eluser]
If it doesn't use any of the existing error functionality you could just put it in a helper. Perhaps make error_helper.php, any functions in that file will be available globally once it's loaded into your controller - or auto-loaded.
#3

[eluser]the real rlee[/eluser]
Ahh thanks! I was overlooking the obvious there!
#4

[eluser]the real rlee[/eluser]
For anyone referring to this thread here's how i created my custom error:

Extended Exceptions Library (My_Exceptions) (CI uses this to create its own global show_error(), show_404() functions)
Code:
class MY_Exceptions extends CI_Exceptions {

    function MY_Exceptions(){
        parent::CI_Exceptions();
    }
    
    function show_401()
    {    
        $heading = "401 Not Authorized";
        $message = "You are not authorized to view this page.";
        
        echo $this->show_error($heading, $message, 'error_401');
        exit;
    }
    
}

Created a helper (helpers/error_helper.php) for my custom function which i autoload (CI does this within CodeIgniter/Common)
Code:
function show_401(){
    $exceptions =& load_class('Exceptions');
    $exceptions->show_401();
    
}

Created by own errors page (applications/errors/error_401.php)

Code:
<?php header("HTTP/1.1 401 Unauthorized"); ?>
<html>
<head>
<title>401 Unauthorized</title>
<style type="text/css">

body {
background-color:    #fff;
margin:                40px;
font-family:        Lucida Grande, Verdana, Sans-serif;
font-size:            12px;
color:                #000;
}

#content  {
border:                #999 1px solid;
background-color:    #fff;
padding:            20px 20px 12px 20px;
}

h1 {
font-weight:        normal;
font-size:            14px;
color:                #990000;
margin:             0 0 4px 0;
}
</style>
</head>
<body>
    <div id="content">
        <h1>&lt;?php echo $heading; ?&gt;</h1>
        &lt;?php echo $message; ?&gt;
        <p>&lt;?=anchor('user/login', 'Please login to continue')?&gt;</p>
    </div>
&lt;/body&gt;
&lt;/html&gt;

And hey presto (example usage):

Code:
Admin extends Controller {

   function admin(){
      parent::Controller();

      if (!$this->user_auth->is_logged_in()) {
         show_401();
      }
    
   }
}




Theme © iAndrew 2016 - Forum software by © MyBB