Source for file exception.classe.php

Documentation is available at exception.classe.php

  1. <?php
  2.  
  3.  
  4.  
  5. /**
  6.  * Função errorHandler para manusear as exceptions que forem lançadas fora de um bloco try/catch
  7.  * Irá imprimir em tela uma mensagem dizendo o arquivo em linha onde deve ser implementado um bloco
  8.  * try/catch
  9.  * @param Object $exception Objeto da exceção lançada
  10.  * @return void 
  11.  */
  12. function exceptionHandler($exception){
  13.     /**
  14.      * Se o tipo de erro estiver configurado para ser mostrado em tela
  15.      * Esta diretiva deve ser definida no config.exception.php
  16.      */
  17.     if(isset($exception)){
  18.         if($exception->getDisplayErro()){
  19.             /**
  20.              * Verifica se a exceção não foi lançada por um sistema externo
  21.              */
  22.             if(!verificaExceptionSistemaExterno($exception->getArquivoErroFaltaTryCatch())){
  23.                    echo $exception->getMensagemFaltaBlocoTryCatch();
  24.             }
  25.         }
  26.     }
  27. }
  28.  
  29. /**
  30.  * Define o tratador de exceção exceptionHandler padrão se uma exceção não for pega em um bloco
  31.  * try/catch
  32.  */
  33. set_exception_handler('exceptionHandler');
  34.  
  35.  
  36. /**
  37.  * Classe de Exceptions base do Framework da Áton. Todas as classes de Exception a serem criadas devem herdar
  38.  * essa classe
  39.  *
  40.  * @author Jonas Beto Rompkovski <jonasbeto.rompkovski@gmail.com>
  41.  * @version 0.1
  42.  * @since 18/12/2006
  43.  * @package exception
  44.  */
  45. class exception extends Exception {
  46.     
  47.     /**
  48.      * @var String Nome da Exceção que lançou o erro
  49.      * @access protected
  50.      */
  51.     protected $classeErro;
  52.     
  53.     /**
  54.      * @var String Mensagem técnica para erros provindos de tempo de execuçao ou erros for�ados pelo usuário
  55.      * @access protected
  56.      */
  57.     protected $strMensagemTecnica;
  58.     
  59.     protected $strContexto;
  60.     
  61.     /**
  62.      * @var Timestamp Data e Hora do erro
  63.      */
  64.     protected $date;
  65.     
  66.     /**
  67.      * @var Integer código de erro em tempo de excução
  68.      */
  69.     protected $intNivel;
  70.     
  71.     /**
  72.      * @var Integer Número identificador (ID) do erro
  73.      */
  74.     private $intNumeroErroAtual 1;
  75.     
  76.     private $intNumeroErros 0;
  77.     
  78.     /**
  79.      * Construtor da classe
  80.      * @param String $strMensagem Descrição do Erro/Exception
  81.      * @param Integer $intErro Número do tipo de erro ocorrido
  82.      */
  83.     public function __construct($strMensagem$intErro 0){
  84.         //definindo a data e hora em que ocorreu o erro
  85.         $this->setData();
  86.            parent::__construct($strMensagem$intErro);
  87.     }
  88.     
  89.     /**
  90.      * Define a mensagem da Exceção
  91.      * @param String $strMensagem Mensagem
  92.      * @return Void 
  93.      */
  94.     protected function setMensagem($strMensagem){
  95.         $this->message $strMensagem;
  96.     }
  97.     
  98.     /**
  99.      * Função que captura a mensagem do erro
  100.      * @return String 
  101.      */
  102.     public function getMensagem(){
  103.         return $this->message;
  104.     }
  105.     
  106.     /**
  107.      * Função que retorna o número do tipo de erro
  108.      */
  109.     public function getTipoErro(){
  110.         return $this->code;
  111.     }
  112.     
  113.     /**
  114.      * Retorna o valor das diretivas definidas na configuração. Se retornar 1, quer dizer que o erro
  115.      * será mostrado na tela
  116.      * @return Boolean 
  117.      */
  118.     public function getDisplayErro(){
  119.         switch ($this->getTipoErro()){
  120.             case E_ERROR:
  121.                 return CFG_EXCEPTION_DISPLAY_ERROR;
  122.                 break;
  123.             case E_WARNING:
  124.                 return CFG_EXCEPTION_DISPLAY_WARNING;
  125.                 break;
  126.             case E_PARSE:
  127.                 return CFG_EXCEPTION_DISPLAY_PARSE;
  128.                 break;
  129.             case E_NOTICE:
  130.                 return CFG_EXCEPTION_DISPLAY_NOTICE;
  131.                 break;
  132.             case E_CORE_ERROR:
  133.                 return CFG_EXCEPTION_DISPLAY_CORE_ERROR;
  134.                 break;
  135.             case E_CORE_WARNING:
  136.                 return CFG_EXCEPTION_DISPLAY_CORE_WARNING;
  137.                 break;
  138.             case E_COMPILE_ERROR:
  139.                 return CFG_EXCEPTION_DISPLAY_COMPILE_ERROR;
  140.                 break;
  141.             case E_COMPILE_WARNING:
  142.                 return CFG_EXCEPTION_DISPLAY_COMPILE_WARNING;
  143.                 break;
  144.             case E_USER_ERROR:
  145.                 return CFG_EXCEPTION_DISPLAY_USER_ERROR;
  146.                 break;
  147.             case E_USER_WARNING:
  148.                 return CFG_EXCEPTION_DISPLAY_USER_WARNING;
  149.                 break;
  150.             case E_USER_NOTICE:
  151.                 return CFG_EXCEPTION_DISPLAY_USER_NOTICE;
  152.                 break;
  153.             case E_STRICT:
  154.                 return CFG_EXCEPTION_DISPLAY_STRICT;
  155.                 break;
  156.             default:
  157.                 return 1;
  158.                 break;
  159.         }
  160.     }
  161.     
  162.     /**
  163.      * Retorna o valor das diretivas definidas na configuração. Se retornar 1, quer dizer que o erro
  164.      * será salvo no arquivo de log
  165.      * @return Boolean 
  166.      */
  167.     public function getBuildLog(){
  168.         switch ($this->getTipoErro()){
  169.             case E_ERROR:
  170.                 return CFG_EXCEPTION_BUILD_LOG_ERROR;
  171.                 break;
  172.             case E_WARNING:
  173.                 return CFG_EXCEPTION_BUILD_LOG_WARNING;
  174.                 break;
  175.             case E_PARSE:
  176.                 return CFG_EXCEPTION_BUILD_LOG_PARSE;
  177.                 break;
  178.             case E_NOTICE:
  179.                 return CFG_EXCEPTION_BUILD_LOG_NOTICE;
  180.                 break;
  181.             case E_CORE_ERROR:
  182.                 return CFG_EXCEPTION_BUILD_LOG_CORE_ERROR;
  183.                 break;
  184.             case E_CORE_WARNING:
  185.                 return CFG_EXCEPTION_BUILD_LOG_CORE_WARNING;
  186.                 break;
  187.             case E_COMPILE_ERROR:
  188.                 return CFG_EXCEPTION_BUILD_LOG_COMPILE_ERROR;
  189.                 break;
  190.             case E_COMPILE_WARNING:
  191.                 return CFG_EXCEPTION_BUILD_LOG_COMPILE_WARNING;
  192.                 break;
  193.             case E_USER_ERROR:
  194.                 return CFG_EXCEPTION_BUILD_LOG_USER_ERROR;
  195.                 break;
  196.             case E_USER_WARNING:
  197.                 return CFG_EXCEPTION_BUILD_LOG_USER_WARNING;
  198.                 break;
  199.             case E_USER_NOTICE:
  200.                 return CFG_EXCEPTION_BUILD_LOG_USER_NOTICE;
  201.                 break;
  202.             case E_STRICT:
  203.                 return CFG_EXCEPTION_BUILD_LOG_STRICT;
  204.                 break;
  205.             default:
  206.                 return 1;
  207.                 break;
  208.         }
  209.     }
  210.     
  211.     /**
  212.      * Define o código da Exceção definido pelo usuário
  213.      * @param Integer $inrCodigo código da Exceção
  214.      * @return Void 
  215.      */
  216.     protected function setCodigo($intCodigo){
  217.         $this->code $intCodigo;
  218.     }
  219.     
  220.     /**
  221.      * Define o nome do arquivo gerador da Exceção
  222.      * @param String $strNomeArquivo description
  223.      * @return Void 
  224.      */
  225.     protected function setNomeArquivo($strNomeArquivo){
  226.         $this->file $strNomeArquivo;
  227.     }
  228.  
  229.     /**
  230.      * Define a linha que gerou a Exceção
  231.      * @param Integer $intLinha Número da Linha
  232.      * @return Void 
  233.      */
  234.     protected function setLinha($intLinha){
  235.         $this->line $intLinha;
  236.     }
  237.     
  238.     /**
  239.      * Define a dara em que o erro/exceção foi gerado
  240.      */
  241.     protected function setData(){
  242.         setlocale (LC_ALL'pt_BR');
  243.         $this->date = date("d/m/Y H:i:s");
  244.     }
  245.     
  246.     /**
  247.      * Retorna o Índice da Pilha que mostra onde o erro realmente ocorreu
  248.      * @return Integer 
  249.      */
  250.     private function getIndicePilha(){
  251.         if($this->classeErro == CFG_EXCEPTION_TEMPO_EXCECUCAO){
  252.             if($this->getTipoErro(== E_USER_ERROR || $this->getTipoErro(== E_USER_WARNIG || $this->getTipoErro(== E_USER_NOTICE){
  253.                 return 2;
  254.             }else{   
  255.                 return 1;
  256.             }
  257.         }
  258.         else{
  259.             return 1;
  260.         }
  261.     }
  262.     
  263.     /**
  264.      * Retorna o caminho completo e nome do arquivo que gerou a Exceção.
  265.      * @return String 
  266.      */
  267.     public function getCaminhoArquivoErro(){
  268.         $ar $this->getTrace();
  269.         //echo "<pre>";
  270.         //print_r($this->getTrace());
  271.         return $ar[$this->getIndicePilha()]['file'];
  272.     }
  273.     
  274.     /**
  275.      * Retorna o nome do arquivo que gerou a Exceção.
  276.      * @return String 
  277.      */
  278.     public function getNomeArquivoErro(){
  279.         $ar $this->getTrace();
  280.         $caminho $ar[$this->getIndicePilha()]['file'];
  281.         $arAux explode("/"$caminho);
  282.         return $arAux[(count($arAux)-1)];
  283.     }
  284.     
  285.     /**
  286.      * Retorna o Número da linha em que ocorreu o erro
  287.      * @return Integer 
  288.      */
  289.     public function getLinhaErro(){
  290.         $ar $this->getTrace();
  291.         return $ar[$this->getIndicePilha()]['line'];
  292.     }
  293.     
  294.     /**
  295.      * Retorna o Índice da Pilha que mostra onde faltou o bloco de try/catch
  296.      * @return Integer 
  297.      */
  298.     private function getIndicePilhaFaltaTryCatch(){
  299.         if($this->classeErro == CFG_EXCEPTION_TEMPO_EXCECUCAO){
  300.             return 2;
  301.         }
  302.         else{
  303.             return 1;
  304.         }
  305.     }
  306.     
  307.     /**
  308.      * Retorna o nome e caminho completo do arquivo onde faltou o bloco de try/catch.
  309.      * @return String 
  310.      */
  311.     public function getArquivoErroFaltaTryCatch(){
  312.         $ar $this->getTrace();
  313.         return $ar[$this->getIndicePilhaFaltaTryCatch()]['file'];
  314.     }
  315.     
  316.     /**
  317.      * Retorna o Número da linha onde faltou o bloco de try/catch
  318.      * @return Integer 
  319.      */
  320.     public function getLinhaErroFaltaTryCatch(){
  321.         $ar $this->getTrace();
  322.         if($this->classeErro == CFG_EXCEPTION_TEMPO_EXCECUCAO){
  323.             return $ar[$this->getIndicePilhaFaltaTryCatch()]['line'];
  324.         }
  325.         else{
  326.             return $ar[$this->getIndicePilhaFaltaTryCatch()-1]['line'];
  327.         }
  328.     }
  329.     
  330.     /**
  331.      * Retorna a função/método onde faltou o bloco de try/catch
  332.      * @return Integer 
  333.      */
  334.     public function getFuncaoErroFaltaTryCatch(){
  335.         $ar $this->getTrace();
  336.         if($this->classeErro == CFG_EXCEPTION_TEMPO_EXCECUCAO){
  337.             return $ar[$this->getIndicePilhaFaltaTryCatch()]['function'];
  338.         }
  339.         else{
  340.             return $ar[$this->getIndicePilhaFaltaTryCatch()]['function'];
  341.         }
  342.     }
  343.        
  344.     /**
  345.      * Monta uma string com o erro técnico
  346.      * @return String 
  347.      */    
  348.     public function __toString(){
  349.         $str  CFG_LOG_EXCEPTION_INICIO;
  350.         $str .= CFG_LOG_EXCEPTION_MENSAGEM_USUARIO.$this->message.CFG_LOG_EXCEPTION_INFORME$this->intNumeroErroAtual."\n";
  351.         $str .= CFG_LOG_EXCEPTION_DATA.$this->date."\n";
  352.         $str .= CFG_LOG_EXCEPTION_CODIGO.$this->intNumeroErroAtual."\n";
  353.         if($this->classeErro != CFG_EXCEPTION_TEMPO_EXCECUCAO){
  354.             $str .= CFG_LOG_EXCEPTION_EXCEPTION.$this->classeErro."\n";
  355.         }
  356.         else{
  357.             $str .= CFG_LOG_EXCEPTION_ERRO_SISTEMA;
  358.             switch ($this->intNivel{
  359.                 case E_WARNING:
  360.                     $str .= CFG_LOG_EXCEPTION_WARNING
  361.                     break;
  362.                 case E_NOTICE:
  363.                     $str .= CFG_LOG_EXCEPTION_NOTICE;
  364.                     break;
  365.                 case E_STRICT:
  366.                     $str .= CFG_LOG_EXCEPTION_STRICT;
  367.                     break;
  368.                 case E_USER_ERROR:
  369.                     $str .= CFG_LOG_EXCEPTION_ERRO_USUARIO;
  370.                     break;
  371.                 case E_USER_WARNING:
  372.                     $str .= CFG_LOG_EXCEPTION_WARNING_USUARIO;
  373.                     break;
  374.                 case E_USER_NOTICE:
  375.                     $str .= CFG_LOG_EXCEPTION_NOTICE_USUARIO;
  376.                     break;
  377.                 default:
  378.                     $str .= CFG_LOG_EXCEPTION_ERRO_DESCONHECIDO;
  379.             }
  380.             $str .= CFG_LOG_EXCEPTION_MENSAGEM_TECNICA.$this->strMensagemTecnica."\n";
  381.         }
  382.         //$str .= CFG_LOG_EXCEPTION_NOME_ARQUIVO.$this->getNomeArquivoErro()."\n";
  383.         $str .= CFG_LOG_EXCEPTION_CAMINHO_ARQUIVO.$this->getCaminhoArquivoErro()."\n";
  384.         $str .= CFG_LOG_EXCEPTION_LINHA.$this->getLinhaErro()."\n";
  385.         $str .= CFG_LOG_EXCEPTION_PILHA;
  386.         $str .= $this->getTraceAsString()."\n";
  387.         $str .= CFG_LOG_EXCEPTION_FIM;
  388.         return $str;
  389.     }
  390.     
  391.     /**
  392.      * Verifica o ultimo código de log e adiciona mais 1 para então ser usado em um novo registro do
  393.      * log
  394.      * @return Void 
  395.      */
  396.     private function setProximoNumeroErro(){
  397.         $this->intNumeroErroAtual 1;
  398.         if($handle fopen (CFG_EXCEPTION_CAMINHO_ARQUIVO_LOG"r")){
  399.             while (!feof ($handle)) {
  400.                 $buffer fgets($handle);
  401.                 if(strpos($bufferCFG_LOG_EXCEPTION_CODIGO_BUSCA)){
  402.                     $arAux explode(":"$buffer);
  403.                     $this->intNumeroErroAtual $arAux[1]+1;
  404.                 }
  405.                 if(strpos($bufferCFG_LOG_EXCEPTION_INICIO)){
  406.                     $this->intNumeroErros++;
  407.                 }
  408.                 
  409.             }
  410.             fclose ($handle);
  411.         }
  412.         else{
  413.             throw new ioException();
  414.         }
  415.     }
  416.     
  417.     private function buildLimiteErros(){
  418.         if($this->intNumeroErros>2){
  419.             $intIniciar $this->intNumeroErros 2;
  420.             $i 0;
  421.             $str "";
  422.             
  423.                        
  424.             $handle fopen (CFG_EXCEPTION_CAMINHO_ARQUIVO_LOG"r");
  425.             while (!feof ($handle)) {
  426.                 $buffer fgets($handle);
  427.                 if(strpos($bufferCFG_LOG_EXCEPTION_INICIO)){
  428.                     $i++;
  429.                 }
  430.                 if($i>=$intIniciar){
  431.                     $str .= $buffer."\r";
  432.                 }
  433.             }
  434.             fclose ($handle);
  435.             
  436.             $arq new arquivo();
  437.             $arq->setNomeArquivo(CFG_EXCEPTION_NOME_ARQUIVO_LOG);
  438.             $arq->setExtensaoArquivo(CFG_EXCEPTION_EXTENSAO_ARQUIVO_LOG);
  439.             $arq->strModoGravacao "w+";  
  440.             $arq->setConteudo($str);
  441.             $arq->buildArquivo();
  442.         }
  443.     }
  444.     
  445.     /**
  446.      * Adiciona o erro ao arquivo de log
  447.      */
  448.     public function buildLog(){
  449.         try{
  450.             if($this->getBuildLog()){
  451.                 $this->setProximoNumeroErro();
  452.                 
  453.                 $arq new arquivo();
  454.                 
  455.                 $arq->setNomeArquivo(CFG_EXCEPTION_NOME_ARQUIVO_LOG);
  456.                 $arq->setExtensaoArquivo(CFG_EXCEPTION_EXTENSAO_ARQUIVO_LOG);
  457.                 $arq->strModoGravacao "a+";
  458.                 $arq->setConteudo($this->__toString());
  459.                 $arq->buildArquivo();
  460.                 
  461.                 
  462.                 if($this->getDisplayErro()){
  463.                     $this->buildSmartyMessage();
  464.                 }
  465.                 //$this->buildSmartyMessage();
  466.             }else{
  467.                 if($this->getDisplayErro()){
  468.                     $this->buildSmartyMessage();
  469.                 }
  470.             }
  471.         }
  472.         catch(Exception $e){
  473.             $e->getStringErroUsuario();
  474.         }
  475.     }
  476.     
  477.  
  478.     /**
  479.      * método chamado quando uma função lançar uma Exceção fora do bloco
  480.      * try/catch
  481.      * @return String 
  482.      */   
  483.     public function getMensagemFaltaBlocoTryCatch(){
  484.         $str  "- <b>Há necessidade de se implementar um blobo de try/catch!</b><br>";
  485.         $str .= "- <b>Nome e Caminho do Arquivo:</b> ".$this->getArquivoErroFaltaTryCatch()."<br>";
  486.         $str .= "- <b>Função/Método:</b> ".$this->getFuncaoErroFaltaTryCatch()."<br>";
  487.         $str .= "- <b>Linha onde será lançado a exceção:</b> ".$this->getLinhaErroFaltaTryCatch()."<br>";
  488.         $str .= "- <b>Exceção que será lançada:</b> ".$this->classeErro."<br>";
  489.         return $str;
  490.     }
  491.     
  492.     
  493.     
  494.     /**
  495.      * Retorna o erro do usuário
  496.      */
  497.     public function getStringErroUsuario(){
  498.         return $this->messageCFG_LOG_EXCEPTION_INFORME$this->intNumeroErroAtual;
  499.     }
  500.     
  501.     /**
  502.      * Gera as mensagens de erro e retorna ao smarty
  503.      */
  504.     public function buildSmartyMessage(){
  505.         require_once(CFG_LOCAL_FRAMEWORK.'sm.classe.php');
  506.         $sm new sm(CFG_LOCAL_FRAMEWORK."/t/");
  507.         if($this->intNivel == E_STRICT){
  508.             $str  CFG_LOG_EXCEPTION_STRICT."<br>";
  509.             $str .= CFG_LOG_EXCEPTION_MENSAGEM_TECNICA.$this->strMensagemTecnica."<br>";
  510.             $str .= CFG_LOG_EXCEPTION_CAMINHO_ARQUIVO.$this->getCaminhoArquivoErro()."<br>";
  511.             $str .= CFG_LOG_EXCEPTION_LINHA.$this->getLinhaErro()."\n";
  512.             $sm->assign('msg'$str);
  513.         }else{
  514.             if(CFG_EXCEPTION_DISPLAY == CFG_EXCEPTION_DISPLAY_USUARIO){
  515.                 $sm->assign('msg'$this->getStringErroUsuario());
  516.             }elseif(CFG_EXCEPTION_DISPLAY == CFG_EXCEPTION_DISPLAY_TECNICO){
  517.                 $sm->assign('msg'str_replace("\n","<br>",$this->getStringErroTecnico())."<br>");
  518.             }
  519.         }
  520.         $sm->display(CFG_EXCEPTION_SMARTY);
  521.     }
  522.  
  523.     
  524.     /**
  525.      * Retorna o erro técnico
  526.      */
  527.     public function getStringErroTecnico(){
  528.         return $this->__toString();
  529.     }
  530.     
  531.     public function enabledErrorHandler(){
  532.         set_error_handler('errorHandler');
  533.         ini_set('html_errors',false);
  534.         ini_set('error_prepend_string','<html><head><META http-equiv="refresh" content="0;URL='.CFG_ERROR_FATAL_HANDLER);
  535.         ini_set('error_append_string','"></head></html>');
  536.     }
  537.     
  538.     public function disabledErrorHandler(){
  539.         set_error_handler(null);
  540.         ini_set('html_errors',false);
  541.         ini_set('error_prepend_string',null);
  542.         ini_set('error_append_string',null);
  543.     }
  544. }
  545. ?>

Documentation generated on Sun, 09 Mar 2008 23:51:49 -0300 by phpDocumentor 1.4.0

SourceForge.net Logo Support This Project