예외가 실제로 가장 좋은 옵션이며, 사용자가 요청한 모든 것을 수행합니다. 예외는 확장 할 수있는 클래스이므로 여러 메시지도 가능합니다. 예외를 발생시키는 객체를 예외로 전달할 수 있습니다.
<?php
class ExampleException extends Exception {
private $secondMessage;
private $objectThatCausedIt;
public function __construct($secondMessage, $objectThatCausedIt) {
parent::__construct(
"Descriptive message for developer",
// error code for this type of error
1000);
$this->secondMessage = $secondMessage;
$this->objectThatCausedIt = $objectThatCausedIt;
}
public function getSecondMessage() {
return $this->secondMessage;
}
public function getObjectThatCausedIt() {
return $this->objectThatCausedIt;
}
}
class Example {
public function causeException() {
throw new ExampleException("Second Message", $this);
}
}
이제 클래스를 사용하고 예외를 throw 할 수있는 호출을 try-catch 블록으로 래핑합니다.
<?php
$example = new Example();
try {
$example->causeException();
}
catch (ExampleException $e) {
// kind of pointless here, just an illustration
// get object that caused it and do something with it.
dump_and_log_function($e->getObjectThatCausedIt());
// or just use $example, which is still "alive"
// and references the same instance
dump_and_log_function($example);
}
Extending Exception은 스택 백 트레이스를 얻는 이점이 있습니다. 백 트레이스에는 예외가 발생한 파일, 라인 및 기능과 같은 정보가 들어 있습니다. 또한 오류 코드, 메시지 등에 액세스 할 수 있습니다. 자세한 내용은 예외 (http://php.net/manual/en/class.exception.php)의 PHP 설명서를 읽으십시오.
오류 메시지와 로깅에 관해서는 대개 싱글 톤 클래스를 사용합니다.
<?php
class Log {
private $logFile;
private static $instance;
/* Log instances may only be constructed in Log::getInstance */
private function __construct() {
$this->logFile = fopen("path/to/log/file", "a");
}
public logMessage($message) {
fwrite($this->logFile, $message);
}
public static getInstance() {
if (!self::$instance) self::$instance = new self();
return self::$instance;
}
}
지금 다시 예외 처리 던져-catch 블록에 가고, 당신이 그것을 변경할 수 있습니다 에 : 싱글 톤 클래스 (. 경우에 당신이 모르는) 다음은 매우 간단한 예입니다 자체의 단 하나의 인스턴스가
<?php
$example = new Example();
try {
$example->causeException();
}
catch (ExampleException $e) {
// log developer message and backtrace
Log::getInstance()->logMessage($e->getMessage());
Log::getInstance()->logMessage($e->getTraceAsString());
// or more compact by casting to string
Log::getInstance()->logMessage((string)$e);
// and now print error for users
echo "<p>An Error has occured: {$e->getSecondMessage()}</p>";
}
오류 메시지가 바로 표시되는 대신 Log 클래스에 메시지 배열이있는 속성을 만들 수 있습니다. 그런 다음 나중에보기 스크립트에 한 번에 나열 할 수 있습니다. logMessage 메소드가 메시지를 세션에 저장하여 새로 고친 후에 표시되도록 할 수도 있습니다 (세션에서 메시지를 지우는 것을 잊지 않거나 계속 표시됩니다 ;-).
첫 번째 대답은 무엇인가요? SO에 오신 것을 환영합니다! –