CakePHP 오류 및 예외 처리

WBOY
풀어 주다: 2024-09-10 17:26:09
원래의
626명이 탐색했습니다.

시스템의 원활한 운영을 위해서는 시스템 장애에 대한 효율적인 처리가 필요합니다. CakePHP에는 오류가 발생할 때 이를 인쇄하고 기록하는 기본 오류 추적 기능이 포함되어 있습니다. 동일한 오류 처리기가 예외를 포착하는 데 사용됩니다.

오류 핸들러는 디버그가 true인 경우 오류를 표시하고 디버그가 false인 경우 오류를 기록합니다. CakePHP에는 다양한 예외 클래스가 있으며 내장된 예외 처리 기능이 포착되지 않은 모든 예외를 캡처하고 유용한 페이지를 렌더링합니다.

오류 및 예외 구성

오류 및 예외는 configapp.php 파일에서 구성할 수 있습니다. 오류 처리에서는 애플리케이션에 맞게 오류 처리를 맞춤화할 수 있는 몇 가지 옵션을 허용합니다. −

를 구현해야 합니다.
옵션 데이터 유형 설명
오류레벨 정수
Option Data Type Description
errorLevel int

The level of errors you are interested in capturing. Use the built-in php error constants, and bitmasks to select the level of error you are interested in.

trace bool

Include stack traces for errors in log files. Stack traces will be included in the log after each error. This is helpful for finding where/when errors are being raised.

exceptionRenderer string

The class responsible for rendering uncaught exceptions. If you choose a custom class, you should place the file for that class in src/Error. This class needs to implement a render() method.

log bool

When true, exceptions + their stack traces will be logged to CakeLogLog.

skipLog array

An array of exception class names that should not be logged. This is useful to remove NotFoundExceptions or other common, but uninteresting logs messages.

extraFatalErrorMemory int

Set to the number of megabytes to increase the memory limit by, when a fatal error is encountered. This allows breathing room to complete logging or error handling.

캡처하려는 오류 수준입니다. 내장된 PHP 오류 상수와 비트마스크를 사용하여 관심 있는 오류 수준을 선택하세요.
추적 부울

로그 파일에 오류에 대한 스택 추적을 포함합니다. 각 오류 이후에는 스택 추적이 로그에 포함됩니다. 이는 언제 어디서 오류가 발생하는지 찾는 데 도움이 됩니다.

ExceptionRenderer 문자열

잡히지 않는 예외를 렌더링하는 클래스입니다. 사용자 정의 클래스를 선택하는 경우 해당 클래스에 대한 파일을

src/Error

에 배치해야 합니다. 이 클래스는 render() 메소드

로그 부울
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('/exception/:arg1/:arg2',
      ['controller'=>'Exps','action'=>'index'],
      ['pass' => ['arg1', 'arg2']]);
   $builder->fallbacks();
});
로그인 후 복사
참인 경우 예외와 해당 스택 추적이

CakeLogLog에 기록됩니다.

skipLog 배열 기록하면 안 되는 예외 클래스 이름의 배열입니다. 이는 NotFoundExceptions 또는 기타 일반적이지만 흥미롭지 않은 로그 메시지를 제거하는 데 유용합니다.

extraFatalErrorMemory 정수 치명적인 오류가 발생한 경우 메모리 제한을 늘릴 메가바이트 수를 설정합니다. 이를 통해 로깅 또는 오류 처리를 완료할 여유가 있습니다.
<?php namespace App\Controller;
   use App\Controller\AppController;
   use Cake\Core\Exception\Exception;
   class ExpsController extends AppController {
      public function index($arg1,$arg2) {
         try{
            $this->set('argument1',$arg1);
            $this->set('argument2',$arg2);
            if(($arg1 > 1 || $arg1 > 10) || ($arg2  10))
               throw new Exception("One of the number is out of range [1-10].");
         } catch(\Exception $ex){
            echo $ex->getMessage();
         }
      }
   }
?>
로그인 후 복사

config/routes.php 파일을 다음 코드와 같이 변경하세요. config/routes.php

src/Controller/ExpsController.php에
This is CakePHP tutorial and this is an example of Passed arguments.<br>
Argument-1: =$argument1?><br>
Argument-2: =$argument2?><br>
로그인 후 복사
ExpsController.php

파일을 생성합니다.

컨트롤러 파일에 다음 코드를 복사합니다.

src/Controller/ExpsController.php

CakePHP 오류 및 예외 처리src/Template에 Exps 디렉토리를 만들고 해당 디렉토리 아래에 index.php라는 View 파일을 만듭니다. 해당 파일에 다음 코드를 복사하세요. src/Template/Exps/index.php 다음 URL에 접속하여 위의 예시를 실행해 보세요. http://localhost/cakephp4/Exception/5/0 출력 실행하면 다음과 같은 결과가 출력됩니다.

위 내용은 CakePHP 오류 및 예외 처리의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!