lighthouse/error-handler 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

lighthouse/error-handler

最新稳定版本:v0.1.0

Composer 安装命令:

composer require lighthouse/error-handler

包简介

Error and Exception Handler for the Lighthouse framework

README 文档

README

Error and Exception Handler for the Lighthouse framework.

Installation

composer require lighthouse/error-handler

Requirements

  • PHP 8.2 or higher

Features

  • Debug and production error pages
  • HTTP exception classes (404, 401, 403, 405, etc.)
  • HTML and JSON error renderers
  • PSR-15 error middleware
  • Custom renderer support
  • Error logging integration

Quick Start

Basic Usage

use Lighthouse\ErrorHandler\ErrorHandler;
use Lighthouse\ErrorHandler\Exception\NotFoundException;

// Create handler with response factory
$errorHandler = new ErrorHandler(
    debug: true, // Set to false in production
    responseFactory: fn(int $status) => new Response($status)
);

// Handle an exception
try {
    throw new NotFoundException('Page not found');
} catch (Throwable $e) {
    $response = $errorHandler->handle($e, $request);
}

HTTP Exceptions

Throw HTTP-specific exceptions:

use Lighthouse\ErrorHandler\Exception\NotFoundException;
use Lighthouse\ErrorHandler\Exception\BadRequestException;
use Lighthouse\ErrorHandler\Exception\UnauthorizedException;
use Lighthouse\ErrorHandler\Exception\ForbiddenException;
use Lighthouse\ErrorHandler\Exception\MethodNotAllowedException;
use Lighthouse\ErrorHandler\Exception\HttpException;

// 404 Not Found
throw new NotFoundException('User not found');

// 400 Bad Request
throw new BadRequestException('Invalid email format');

// 401 Unauthorized
throw new UnauthorizedException('Please log in');

// 403 Forbidden
throw new ForbiddenException('Access denied');

// 405 Method Not Allowed
throw new MethodNotAllowedException(['GET', 'POST']);

// Custom status code
throw new HttpException('I am a teapot', 418);

PSR-15 Middleware

Use as middleware in your pipeline:

use Lighthouse\ErrorHandler\ErrorHandler;
use Lighthouse\ErrorHandler\ErrorMiddleware;

$errorHandler = new ErrorHandler(
    debug: getenv('APP_DEBUG') === 'true',
    responseFactory: fn(int $status) => new Response($status)
);

// Create middleware
$errorMiddleware = new ErrorMiddleware($errorHandler);

// Add to pipeline (should be first)
$pipeline->pipe($errorMiddleware);
$pipeline->pipe($routingMiddleware);
$pipeline->pipe($dispatchMiddleware);

Error Logging

Add an error logger:

$errorMiddleware = new ErrorMiddleware(
    $errorHandler,
    function (Throwable $e, ServerRequestInterface $request) use ($logger) {
        $logger->error($e->getMessage(), [
            'exception' => $e,
            'uri' => (string) $request->getUri(),
        ]);
    }
);

Debug vs Production Mode

Debug mode (development):

  • Detailed error page with stack trace
  • Exception class name and file location
  • Request information

Production mode:

  • Clean, user-friendly error page
  • Generic error messages for 500 errors
  • No sensitive information exposed
// Toggle debug mode
$errorHandler->setDebug(false);

JSON Responses

The handler automatically detects Accept: application/json and returns JSON:

{
    "error": {
        "status": 404,
        "message": "User not found"
    }
}

In debug mode:

{
    "error": {
        "status": 404,
        "message": "User not found",
        "type": "Lighthouse\\ErrorHandler\\Exception\\NotFoundException",
        "file": "/app/src/UserController.php",
        "line": 42,
        "trace": [...]
    }
}

Custom Renderers

Create custom error renderers:

use Lighthouse\ErrorHandler\Renderer\RendererInterface;

class XmlRenderer implements RendererInterface
{
    public function render(Throwable $exception, ServerRequestInterface $request): string
    {
        return sprintf(
            '<?xml version="1.0"?><error><message>%s</message></error>',
            htmlspecialchars($exception->getMessage())
        );
    }
}

$errorHandler->registerRenderer('application/xml', new XmlRenderer());

API Reference

ErrorHandler

Method Description
handle(Throwable, ServerRequestInterface) Handle exception and return response
registerRenderer(string $contentType, RendererInterface) Register custom renderer
setDefaultRenderer(RendererInterface) Set default renderer
isDebug() Check if debug mode is enabled
setDebug(bool) Set debug mode

HTTP Exceptions

Exception Status Code
BadRequestException 400
UnauthorizedException 401
ForbiddenException 403
NotFoundException 404
MethodNotAllowedException 405
HttpException Custom

ErrorMiddleware

Method Description
process(ServerRequestInterface, RequestHandlerInterface) PSR-15 middleware
setErrorLogger(callable) Set error logging callback

Testing

composer test

License

MIT License. See LICENSE for details.

Part of the Lighthouse Framework

This package is part of the Lighthouse Framework, an educational PHP framework designed to teach how modern frameworks work internally.

统计信息

  • 总下载量: 11
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-17