错误处理
良好的错误处理机制是 Web 应用的重要组成部分。Kuiper Web 模块基于 Slim 的错误处理中间件, 支持通过 #[ErrorHandler] 属性或配置注册错误处理器,并内置了常用的处理器实现。
错误处理机制
异常处理流程
异常抛出 → ErrorMiddleware 捕获 → 匹配错误处理器 → 错误响应
↓
日志记录(可选)WebConfiguration 注册的 ErrorMiddleware 按异常类型查找处理器:先匹配针对具体异常类注册的 处理器,没有匹配时回退到默认处理器 kuiper\web\handler\ErrorHandler。
异常与状态码
默认处理器按 Slim 的异常体系确定状态码:Slim\Exception\Http*Exception 系列异常使用异常自带的 状态码,其它异常一律 500。抛出对应的 HTTP 异常即可得到期望的状态码:
| 异常 | HTTP 状态码 |
|---|---|
Slim\Exception\HttpBadRequestException | 400 |
Slim\Exception\HttpUnauthorizedException | 401(默认映射,实际被覆盖为 302,见下文) |
Slim\Exception\HttpForbiddenException | 403 |
Slim\Exception\HttpNotFoundException | 404 |
Slim\Exception\HttpMethodNotAllowedException | 405 |
Slim\Exception\HttpNotImplementedException | 501 |
其它 Throwable | 500 |
未授权异常默认跳转登录页
WebConfiguration 默认把 kuiper\web\exception\UnauthorizedException 和 Slim\Exception\HttpUnauthorizedException 都交给 UnauthorizedErrorHandler 处理, 实际行为是 302 跳转到登录页(地址由 application.web.login.url 配置,默认 /login, 跳转地址会附带 redirect 查询参数记录来源页面),而不是返回 401。
内置错误处理器
kuiper\web\handler 命名空间(源码位于 web/src/handler/)提供以下类:
| 类 | 说明 |
|---|---|
ErrorHandler | 默认的通用处理器,按请求的 Accept 头渲染 HTML / XML / JSON 错误响应 |
AbstractErrorHandler | 自定义处理器基类,按内容类型分派到 respondHtml() / respondApi() |
UnauthorizedErrorHandler | 处理未授权异常,302 跳转登录页 |
HttpRedirectHandler | 处理 RedirectException,按异常携带的 URL 重定向 |
LoginUrlBuilderInterface / DefaultLoginUrlBuilder | 构造登录页跳转地址 |
IncludeStacktrace | 堆栈跟踪策略常量(never / always / on_trace_param) |
LogErrorRenderer | 错误日志的渲染器 |
kuiper\web\exception 模块异常
| 异常 | 说明 | 默认处理器 |
|---|---|---|
HttpCsrfTokenException | CSRF 校验失败,继承 HttpBadRequestException | 通用处理器(400) |
HttpRateLimitExceededException | 请求超过速率限制(429) | 通用处理器(429) |
RedirectException | 控制器重定向,ControllerTrait::redirect() 抛出 | HttpRedirectHandler(302) |
UnauthorizedException | 业务未授权 | UnauthorizedErrorHandler(302 跳登录页) |
SessionNotStartException | 会话未启动 | 通用处理器(500) |
ViewException | 视图渲染失败 | 通用处理器(500) |
WebRequestException | Web 请求异常基类 | 通用处理器(500) |
使用 ErrorHandler 属性
属性约束
#[ErrorHandler] 属性(kuiper\web\attribute\ErrorHandler)有以下约束:
- 只能标注在类上(
TARGET_CLASS),不能标注在方法上; - 不可重复标注,同一类上只能出现一次;
- 构造签名是
__construct(string|array $exceptions),可以传单个异常类名,也可以传异常类名数组; - 标注的类本身会被注册为 DI 组件(
ErrorHandler继承自kuiper\di\attribute\Component), 该类必须可调用(即实现__invoke()),不可调用的处理器会被静默跳过。
框架没有 on<异常名>() 之类的错误处理方法分发约定,错误处理统一走可调用对象。
注册错误处理器
写一个可调用类,实现与 Slim\Interfaces\ErrorHandlerInterface 一致的 __invoke() 签名,然后在类上标注 #[ErrorHandler]:
<?php
declare(strict_types=1);
namespace App\handler;
use App\exception\ValidationException;
use kuiper\web\attribute\ErrorHandler;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;
#[ErrorHandler(ValidationException::class)]
final class ValidationFailedHandler
{
public function __construct(
private readonly ResponseFactoryInterface $responseFactory,
) {
}
public function __invoke(
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
): ResponseInterface {
$errors = $exception instanceof ValidationException
? $exception->getErrors()
: [];
$response = $this->responseFactory->createResponse(422)
->withHeader('Content-Type', 'application/json');
$response->getBody()->write((string) json_encode([
'error' => 'validation',
'messages' => $errors,
]));
return $response;
}
}处理多个异常类型
传数组可以让同一个处理器处理多个异常类型。
数组元素里写 ::class 不会生效
组件扫描用 kuiper\reflection 做静态源码解析,数组元素里的 ValidationException::class 会被原样序列化成字符串 "ValidationException::class",注册出的异常键永远匹配不到。
可用写法只有三种:
// ① 顶层类常量(标量参数)
#[ErrorHandler(ValidationException::class)]
// ② 数组 + 字面量类名字符串
#[ErrorHandler([
'App\Exception\ValidationException',
'App\Exception\UserNotFoundException',
])]
// ③ application.web.error.handlers 配置注册处理器必须是可调用的
注册时框架会用 is_callable() 检查处理器实例,不实现 __invoke() 的类会被静默跳过, 对应异常将落到默认处理器上。
通过配置注册
也可以不写属性,直接在 application.web.error.handlers 里按「异常类 => 处理器类」注册:
<?php
// config/config.php
return [
'application' => [
'web' => [
'error' => [
'handlers' => [
\App\exception\ValidationException::class => \App\handler\ValidationFailedHandler::class,
],
],
],
],
];配置注册的处理器同样要求可调用,并且会从容器中解析(构造函数依赖会自动注入)。 属性注册和配置注册可以同时使用。
自定义异常
创建 HTTP 异常
创建继承 Slim HTTP 异常基类的自定义异常,状态码由父类决定。 注意 Slim 的 HttpException 构造函数第一个参数是当前请求:
<?php
declare(strict_types=1);
namespace App\exception;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Exception\HttpNotFoundException;
class UserNotFoundException extends HttpNotFoundException
{
public function __construct(ServerRequestInterface $request, int $userId)
{
parent::__construct($request, "User with ID {$userId} not found");
}
}创建业务异常
创建业务逻辑异常:
<?php
declare(strict_types=1);
namespace App\exception;
use InvalidArgumentException;
class ValidationException extends InvalidArgumentException
{
private array $errors;
public function __construct(array $errors)
{
parent::__construct('Validation failed');
$this->errors = $errors;
}
public function getErrors(): array
{
return $this->errors;
}
}在控制器中抛出异常
<?php
declare(strict_types=1);
namespace App\controller;
use App\exception\UserNotFoundException;
use App\exception\ValidationException;
use App\service\UserService;
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\PostMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
#[Controller]
class UserController extends AbstractController
{
use ControllerTrait;
public function __construct(
private readonly UserService $userService,
) {
}
#[GetMapping('/users/{id}')]
public function show(int $id): ResponseInterface
{
$user = $this->userService->find($id);
if (null === $user) {
throw new UserNotFoundException($this->getRequest(), $id);
}
return $this->json(['success' => true, 'data' => $user]);
}
#[PostMapping('/users')]
public function create(ServerRequestInterface $request): ResponseInterface
{
$data = (array) $request->getParsedBody();
$errors = $this->userService->validate($data, [
'name' => 'required',
'email' => 'required|email',
]);
if (!empty($errors)) {
throw new ValidationException($errors);
}
return $this->json(['success' => true, 'data' => $this->userService->create($data)]);
}
}自定义 HTML 错误页面
继承 AbstractErrorHandler,实现 respondHtml(),用 #[ErrorHandler] 指定要处理的异常:
<?php
declare(strict_types=1);
namespace App\handler;
use kuiper\web\attribute\ErrorHandler;
use kuiper\web\handler\AbstractErrorHandler;
use kuiper\web\view\PhpView;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Exception\HttpNotFoundException;
use Throwable;
#[ErrorHandler(HttpNotFoundException::class)]
final class NotFoundErrorHandler extends AbstractErrorHandler
{
protected function respondHtml(
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails
): ResponseInterface {
$response = $this->getResponseFactory()->createResponse(404);
$response->getBody()->write(
(new PhpView(__DIR__ . '/../../resources/views', '.php'))->render('errors/404', [
'message' => $exception->getMessage(),
])
);
return $response;
}
}错误页面模板 resources/views/errors/404.php(转义用 $__helpers::e()):
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>页面未找到</title>
</head>
<body>
<h1>404 - 页面未找到</h1>
<p><?= $__helpers::e($message) ?></p>
<a href="/">返回首页</a>
</body>
</html>respondHtml() 处理 HTML 请求;JSON/XML 请求会走父类的 respondApi(), 委托给默认处理器渲染。
开发环境错误处理
错误处理相关配置都在 application.web.error 下:
<?php
// config/config.php
return [
'application' => [
'web' => [
'error' => [
// 出错时是否在响应中显示异常详情(环境变量 WEB_ERROR_DISPLAY,默认 false)
'display' => true,
// 是否记录错误日志(环境变量 WEB_ERROR_LOGGING,默认 true)
'logging' => true,
// 堆栈跟踪策略:never / always / on_trace_param
// (环境变量 WEB_ERROR_INCLUDE_STACKTRACE,默认 on_trace_param,
// 即请求带 trace 查询参数时日志中输出堆栈)
'include_stacktrace' => 'always',
],
],
],
];生产环境保持 'display' => false(默认值),只记录日志、返回通用错误信息。
错误日志记录
默认处理器在 logErrors 为 true 时把异常写入日志:Slim 的 HTTP 异常记录为 info, 其它异常记录为 error。日志内容由 LogErrorRenderer 渲染, 堆栈跟踪策略由 application.web.error.include_stacktrace 控制。
自定义处理器里可以按同样的签名处理日志。注意签名是五个参数,不能少:
<?php
declare(strict_types=1);
namespace App\handler;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Slim\Exception\HttpException;
use Throwable;
final class LoggingErrorHandler
{
public function __construct(
private readonly LoggerInterface $logger,
private readonly ResponseFactoryInterface $responseFactory,
) {
}
public function __invoke(
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
): ResponseInterface {
$context = [
'exception' => get_class($exception),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'method' => $request->getMethod(),
'uri' => (string) $request->getUri(),
];
// 4xx 记 warning,5xx 记 error
if ($exception instanceof HttpException && $exception->getCode() < 500) {
$this->logger->warning('Request failed', $context);
} else {
$this->logger->error('Exception occurred', $context);
}
$statusCode = $exception instanceof HttpException ? $exception->getCode() : 500;
$response = $this->responseFactory->createResponse($statusCode)
->withHeader('Content-Type', 'application/json');
$response->getBody()->write((string) json_encode([
'error' => $displayErrorDetails ? $exception->getMessage() : 'An error occurred',
]));
return $response;
}
}完整示例
下面是一个完整的错误处理示例:业务异常类、JSON 错误处理器、控制器与配置。
业务异常 src/exception/ValidationException.php:
<?php
declare(strict_types=1);
namespace App\exception;
use InvalidArgumentException;
class ValidationException extends InvalidArgumentException
{
private array $errors;
public function __construct(array $errors)
{
parent::__construct('Validation failed');
$this->errors = $errors;
}
public function getErrors(): array
{
return $this->errors;
}
}错误处理器 src/handler/ApiErrorHandler.php:
<?php
declare(strict_types=1);
namespace App\handler;
use App\exception\UserNotFoundException;
use App\exception\ValidationException;
use kuiper\web\attribute\ErrorHandler;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Exception\HttpNotFoundException;
use Throwable;
#[ErrorHandler([
'App\Exception\ValidationException',
'App\Exception\UserNotFoundException',
])]
final class ApiErrorHandler
{
public function __construct(
private readonly ResponseFactoryInterface $responseFactory,
) {
}
public function __invoke(
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
): ResponseInterface {
if ($exception instanceof ValidationException) {
$status = 422;
$payload = ['error' => 'validation_error', 'messages' => $exception->getErrors()];
} elseif ($exception instanceof UserNotFoundException
|| $exception instanceof HttpNotFoundException) {
$status = 404;
$payload = ['error' => 'not_found', 'message' => $exception->getMessage()];
} else {
$status = 500;
// 生产环境不暴露详细错误信息
$payload = [
'error' => 'internal_error',
'message' => $displayErrorDetails ? $exception->getMessage() : null,
];
}
$response = $this->responseFactory->createResponse($status)
->withHeader('Content-Type', 'application/json');
$response->getBody()->write((string) json_encode($payload));
return $response;
}
}控制器 src/controller/UserController.php:
<?php
declare(strict_types=1);
namespace App\controller;
use App\exception\UserNotFoundException;
use App\exception\ValidationException;
use App\service\UserService;
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\PostMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
#[Controller]
class UserController extends AbstractController
{
use ControllerTrait;
public function __construct(
private readonly UserService $userService,
) {
}
#[GetMapping('/api/users/{id}')]
public function show(int $id): ResponseInterface
{
$user = $this->userService->find($id);
if (null === $user) {
throw new UserNotFoundException($this->getRequest(), $id);
}
return $this->json(['success' => true, 'data' => $user]);
}
#[PostMapping('/api/users')]
public function create(ServerRequestInterface $request): ResponseInterface
{
$data = (array) $request->getParsedBody();
$errors = $this->userService->validate($data, [
'name' => 'required|string|min:2',
'email' => 'required|email',
'password' => 'required|min:8',
]);
if (!empty($errors)) {
throw new ValidationException($errors);
}
return $this->json(['success' => true, 'data' => $this->userService->create($data)]);
}
}配置 config/config.php(如果想用配置注册而不是 #[ErrorHandler] 属性):
<?php
return [
'application' => [
'web' => [
'error' => [
'display' => false,
'logging' => true,
'handlers' => [
\App\exception\ValidationException::class => \App\handler\ApiErrorHandler::class,
\App\exception\UserNotFoundException::class => \App\handler\ApiErrorHandler::class,
],
],
],
],
];错误处理最佳实践
1. 使用语义化异常
<?php
// 好的做法:使用有意义的异常类
throw new UserNotFoundException($this->getRequest(), $userId);
throw new InvalidTokenException($token);
// 不好的做法:使用通用异常
throw new \RuntimeException('User not found');
throw new \Exception('Invalid token');2. 提供有用的错误信息
<?php
// 好的做法:包含上下文信息
throw new UserNotFoundException(
$this->getRequest(),
$userId
);
// 不好的做法:模糊的错误信息
throw new \Exception('Not found');3. 区分客户端错误和服务端错误
<?php
use Psr\Log\LoggerInterface;
use Slim\Exception\HttpInternalServerErrorException;
use Slim\Exception\HttpNotFoundException;
// 客户端错误(4xx):直接抛 Slim HTTP 异常
if (null === $user) {
throw new HttpNotFoundException($this->getRequest()); // 404
}
if (!empty($errors)) {
throw new ValidationException($errors);
}
// 服务端错误(5xx):记录日志后抛出,由错误处理器返回
try {
$result = $this->externalApi->call($data);
} catch (\Exception $e) {
$this->logger->error('External API failed', ['exception' => $e]);
throw new HttpInternalServerErrorException($this->getRequest()); // 500
}4. 记录异常但不暴露敏感信息
<?php
use Psr\Log\LoggerInterface;
// 好的做法:记录详细信息,返回模糊信息
try {
$this->processPayment($data);
} catch (\Exception $e) {
$this->logger->error('Payment failed', [
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw new PaymentFailedException('Payment processing failed');
}
// 不好的做法:直接暴露内部错误
throw new \Exception('Payment gateway timeout: ' . $e->getMessage());5. 使用适当的 HTTP 状态码
<?php
// 常用状态码
// 400 Bad Request 请求参数错误
// 401 Unauthorized 未认证(默认 302 跳登录页)
// 403 Forbidden 无权限
// 404 Not Found 资源不存在
// 422 Unprocessable Entity 验证失败
// 429 Too Many Requests 速率限制
// 500 Internal Server Error 服务器错误
// 503 Service Unavailable 服务不可用故障排查
异常未被自定义处理器捕获
问题:抛出的异常没有被自定义错误处理器捕获,走了默认处理器。
解决方案:
<?php
// 1. 确认 #[ErrorHandler] 标注在处理器类上(不能标注在控制器或方法上)
// 2. 确认异常类名与注册的一致(含命名空间),或异常是注册异常的子类
// 3. 确认处理器实现了 __invoke(),签名与 ErrorHandlerInterface 一致
// (不可调用的处理器会被静默跳过)
// 4. 或者改用 application.web.error.handlers 配置注册错误响应格式不正确
问题:返回的错误响应格式不符合预期。
解决方案:错误处理器必须返回 ResponseInterface,注意完整签名的五个布尔参数:
<?php
declare(strict_types=1);
namespace App\handler;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;
final class ApiErrorHandler
{
public function __construct(
private readonly ResponseFactoryInterface $responseFactory,
) {
}
public function __invoke(
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
): ResponseInterface {
// 处理器返回的是响应对象,错误内容要自己写进响应体
$response = $this->responseFactory->createResponse(400)
->withHeader('Content-Type', 'application/json');
$response->getBody()->write((string) json_encode(['error' => 'message']));
return $response;
}
}