오류 처리 모범 사례
XOOPS의 오류 처리 모범 사례
섹션 제목: “XOOPS의 오류 처리 모범 사례”적절한 오류 처리는 애플리케이션 안정성, 디버깅 및 사용자 경험에 매우 중요합니다.
예외 계층 구조
섹션 제목: “예외 계층 구조”<?php// Base exceptionclass ModuleException extends \Exception{ protected $statusCode = 500;
public function __construct($message = '', $code = 0, $statusCode = 500) { parent::__construct($message, $code); $this->statusCode = $statusCode; }
public function getStatusCode() { return $this->statusCode; }}
// Specific exceptionsclass ValidationException extends ModuleException{ protected $statusCode = 400; private $errors = [];
public function __construct($message, $errors = []) { parent::__construct($message, 0, 400); $this->errors = $errors; }
public function getErrors() { return $this->errors; }}
class NotFoundException extends ModuleException{ protected $statusCode = 404;}
class UnauthorizedException extends ModuleException{ protected $statusCode = 403;}?>Try-Catch 패턴
섹션 제목: “Try-Catch 패턴”<?phpclass UserService{ public function createUser($username, $email, $password) { try { // Validate $this->validate($username, $email, $password);
// Create user $user = new User(); $user->setUsername($username); $user->setEmail($email); $user->setPassword($password);
// Save $userId = $this->userRepository->save($user);
return $userId;
} catch (ValidationException $e) { \xoops_logger()->error($e->getMessage()); throw $e;
} catch (\Exception $e) { \xoops_logger()->critical($e->getMessage()); throw new \RuntimeException('Failed to create user'); } }}?>로깅 오류
섹션 제목: “로깅 오류”<?phpclass ErrorHandler{ public static function logError($message, $context = []) { \xoops_logger()->error($message, $context); }
public static function logException(\Exception $e) { $context = [ 'exception' => get_class($e), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString(), ];
\xoops_logger()->critical($e->getMessage(), $context); }}?>사용자 친화적인 오류 메시지
섹션 제목: “사용자 친화적인 오류 메시지”<?phpclass ErrorHandler{ public static function getUserMessage(\Exception $e) { switch (true) { case $e instanceof ValidationException: return $e->getMessage();
case $e instanceof NotFoundException: return 'The requested resource was not found.';
case $e instanceof UnauthorizedException: return 'You do not have permission.';
default: return 'An unexpected error occurred.'; } }
public static function getStatusCode(\Exception $e) { if (method_exists($e, 'getStatusCode')) { return $e->getStatusCode(); } return 500; }}?>컨트롤러 오류 처리
섹션 제목: “컨트롤러 오류 처리”<?phpclass UserController{ public function registerAction() { try { if ($_SERVER['REQUEST_METHOD'] !== 'POST') { return []; }
$userId = $this->userService->register( $_POST['username'], $_POST['email'], $_POST['password'] );
return ['success' => true, 'userId' => $userId];
} catch (\Exception $e) { ErrorHandler::logException($e);
return [ 'success' => false, 'message' => ErrorHandler::getUserMessage($e), 'statusCode' => ErrorHandler::getStatusCode($e), ]; } }}?>모범 사례
섹션 제목: “모범 사례”- 특정 예외 유형 생성
- 일찍 던지고 늦게 잡는다
- 컨텍스트와 함께 모든 예외를 기록합니다.
- 사용자 친화적인 메시지 제공
- 일관된 오류 응답 형식을 사용합니다.
- 테스트 오류 처리 경로
- 사용자에게 민감한 정보를 노출하지 마세요.
관련 문서
섹션 제목: “관련 문서”참조:
- 프로젝트 구조에 대한 코드 구성
- 오류 테스트 전략 테스트
- 서비스 예외에 대한../Patterns/Service-Layer
태그: #모범 사례 #오류 처리 #예외 #로깅 #모듈 개발