ctw/ctw-middleware-httpexception 问题修复 & 功能扩展

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

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

ctw/ctw-middleware-httpexception

Composer 安装命令:

composer require ctw/ctw-middleware-httpexception

包简介

This PSR-15 middleware catches exceptions implementing "Ctw\Http\HttpException\HttpException\HttpExceptionInterface" and returns a custom error page.

README 文档

README

Latest Stable Version GitHub Actions Scrutinizer Build Scrutinizer Quality Code Coverage

PSR-15 middleware that catches HTTP exceptions and renders custom error pages for production environments, with automatic JSON support for API requests.

Introduction

Why This Library Exists

Web applications need graceful error handling that presents user-friendly error pages in production while preserving detailed error information during development. The default PHP error handling exposes sensitive information and provides poor user experience.

This middleware integrates with ctw/ctw-http exceptions to:

  • Catch HTTP exceptions: Intercepts exceptions implementing HttpExceptionInterface
  • Render custom templates: Uses Mezzio's template renderer for branded error pages
  • Support JSON responses: Automatically returns RFC 7807 Problem Details for API requests
  • Respect development mode: Re-throws exceptions in development for debugging

Problems This Library Solves

  1. Generic error pages: Default framework error pages are ugly and expose technical details
  2. Missing JSON errors: API clients receive HTML error pages instead of structured JSON
  3. Development vs production: Need different error handling behavior per environment
  4. Inconsistent responses: Different error codes handled inconsistently across the application
  5. Security exposure: Stack traces and internal paths leak in production errors

Where to Use This Library

  • Production web applications: Present branded, user-friendly error pages
  • REST APIs: Return RFC 7807 Problem Details JSON for all HTTP errors
  • Hybrid applications: Automatically serve HTML or JSON based on Accept header
  • Mezzio applications: Integrates seamlessly with the Mezzio template system
  • Multi-environment deployments: Different behavior in development vs production

Design Goals

  1. Content negotiation: Serves HTML or JSON based on client Accept header
  2. RFC 7807 compliance: JSON errors follow Problem Details specification
  3. Template-based rendering: Uses Mezzio template renderer for HTML responses
  4. Development awareness: Re-throws exceptions when development mode is enabled
  5. Exception hierarchy: Only catches HttpExceptionInterface, re-throws others

Requirements

  • PHP 8.3 or higher
  • ctw/ctw-middleware ^4.0
  • ctw/ctw-http ^4.0
  • mezzio/mezzio-template ^2.4
  • mezzio/mezzio-laminasviewrenderer ^2.2

Installation

Install by adding the package as a Composer requirement:

composer require ctw/ctw-middleware-httpexception

Usage Examples

Basic Pipeline Registration (Mezzio)

use Ctw\Middleware\HttpExceptionMiddleware\HttpExceptionMiddleware;

// In config/pipeline.php - place early in the pipeline
$app->pipe(HttpExceptionMiddleware::class);

ConfigProvider Registration

// config/config.php
return [
    // ...
    \Ctw\Middleware\HttpExceptionMiddleware\ConfigProvider::class,
];

Throwing HTTP Exceptions

use Ctw\Http\HttpException;

// In a handler or middleware
throw new HttpException\NotFoundException('Page not found');
throw new HttpException\ForbiddenException('Access denied');
throw new HttpException\InternalServerErrorException('Something went wrong');

HTML Response (Browser)

When a browser requests a page and an exception occurs:

HTTP/1.1 404 Not Found
Content-Type: text/html; charset=UTF-8

<!DOCTYPE html>
<html>
<head><title>404 Not Found</title></head>
<body>
  <h1>Not Found</h1>
  <p>The requested resource could not be found.</p>
</body>
</html>

JSON Response (API)

When a client sends Accept: application/json:

HTTP/1.1 404 Not Found
Content-Type: application/problem+json

{
  "type": "https://httpstatuses.com/404",
  "title": "Not Found",
  "status": 404,
  "detail": "Page not found"
}

Configuration Options

// config/autoload/error-handler.global.php
return [
    'error_handler' => [
        'template_http_exception' => 'error::http-exception',
        'layout' => 'layout::default',
    ],
];
Option Description Default
template_http_exception Template name for HTML error pages error::http-exception.phtml
layout Layout template for error pages (none)

Template Variables

The error template receives:

Variable Type Description
entity HttpStatus HTTP status entity with code, name, phrase
exception HttpExceptionInterface The caught exception
layout string Layout template name (if configured)

Development Mode

In development mode (when laminas/laminas-development-mode is enabled), exceptions are re-thrown to allow the Whoops error handler or similar tools to display detailed debugging information.

ctw/ctw-middleware-httpexception 适用场景与选型建议

ctw/ctw-middleware-httpexception 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 139 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 03 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 ctw/ctw-middleware-httpexception 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 ctw/ctw-middleware-httpexception 我们能提供哪些服务?
定制开发 / 二次开发

基于 ctw/ctw-middleware-httpexception 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2023-03-20