ufutx.love.util/app/Exceptions/Handler.php
2026-04-23 16:11:55 +08:00

156 lines
3.9 KiB
PHP

<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
/**
* 渲染异常为 HTTP 响应
*/
public function render($request, Throwable $e)
{
// API 请求统一返回 JSON 格式
if ($request->expectsJson() || $request->is('api/*')) {
return $this->renderJsonException($e);
}
return parent::render($request, $e);
}
/**
* 将异常渲染为 JSON 格式
*/
protected function renderJsonException(Throwable $e): \Illuminate\Http\JsonResponse
{
// 根据异常类型返回不同的状态码和消息
$statusCode = $this->getStatusCode($e);
$errorCode = $this->getErrorCode($e);
$message = $this->getErrorMessage($e);
$response = [
'code' => 1,
'message' => $message,
'errorCode' => $errorCode,
];
// 开发环境返回调试信息
if (config('app.debug')) {
$response['debug'] = [
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
];
}
return response()->json($response, $statusCode);
}
/**
* 获取 HTTP 状态码
*/
protected function getStatusCode(Throwable $e): int
{
if ($e instanceof NotFoundHttpException) {
return 404;
}
if ($e instanceof ValidationException) {
return 422;
}
if ($e instanceof TypeError) {
return 400; // 参数类型错误
}
if ($e instanceof QueryException) {
return 500;
}
// 如果异常有 getStatusCode 方法(如 Symfony 异常)
if (method_exists($e, 'getStatusCode')) {
return $e->getStatusCode();
}
return 500;
}
/**
* 获取错误代码
*/
protected function getErrorCode(Throwable $e): string
{
return match (true) {
$e instanceof NotFoundHttpException => 'RESOURCE_NOT_FOUND',
$e instanceof ValidationException => 'VALIDATION_ERROR',
$e instanceof TypeError => 'TYPE_ERROR',
$e instanceof QueryException => 'DATABASE_ERROR',
default => 'INTERNAL_SERVER_ERROR',
};
}
/**
* 获取用户友好的错误消息
*/
protected function getErrorMessage(Throwable $e): string
{
// 开发环境返回详细错误
if (config('app.debug')) {
return $e->getMessage();
}
// 生产环境返回友好消息
return match (true) {
$e instanceof NotFoundHttpException => '资源不存在',
$e instanceof ValidationException => '数据验证失败',
$e instanceof TypeError => '参数类型错误',
$e instanceof QueryException => '数据库操作失败',
default => '服务器内部错误,请稍后重试',
};
}
}