异常处理

XinAdmin 项目采用统一的异常处理机制,确保所有异常都能按照统一的格式返回给前端,提高用户体验和系统稳定性。

主要异常类型

HttpResponseException

HttpResponseException 是项目中最常用的自定义异常,用于返回标准格式的响应。它继承自 RuntimeException,并包含以下属性:

  • msg: 响应消息
  • showType: 响应类型(使用 ShowType 枚举)
  • data: 响应数据
  • success: 响应状态

RepositoryException

RepositoryException 是专门用于数据仓库层的异常,继承自 RuntimeException,主要用于处理数据验证、查找失败等情况。

class RepositoryException extends RuntimeException
{
    // 继承 RuntimeException 的功能
}

异常处理方法

使用 Trait

项目提供了 RequestJson trait,其中包含多种异常处理方法:

throwSuccess

抛出成功响应异常,中断程序执行:

$this->throwSuccess(['user' => $user], '用户创建成功');

throwError

抛出错误响应异常,中断程序执行:

$this->throwError([], '操作失败:用户已存在');

throwWarn

抛出警告响应异常,中断程序执行:

$this->throwWarn([], '密码强度较低,建议修改');

notification

返回通知类型的响应:

$this->notification(
    '操作完成', 
    '您的文件已上传成功', 
    ShopTypeEnum::SUCCESS_NOTIFICATION,
    'topRight'
);

使用 HttpResponseException

也可以直接抛出 HttpResponseException

throw new HttpResponseException([
    'success' => false,
    'msg' => '操作失败',
    'data' => [],
    'showType' => ShowType::ERROR_MESSAGE->value
]);

特殊异常处理

验证异常

当请求参数验证失败时,系统会捕获 ValidationException 并返回标准化的错误信息:

ValidationException::class => function (ValidationException $e) {
    return response()->json([
        'msg' => $e->validator->errors()->first(),
        'showType' => ShowType::WARN_MESSAGE->value,
        'success' => false,
    ]);
},

认证异常

当用户未认证时,系统会返回 401 状态码:

AuthenticationException::class => function ($e) {
    return response()->json([
        'msg' => __('user.not_login'),
        'success' => false
    ], 401);
},

权限异常

当用户缺少必要权限时,系统会返回权限不足的通知:

MissingAbilityException::class => function ($e) {
    return $this->notification(
        'No Permission',
        __('system.error.no_permission'),
        ShowType::WARN_NOTIFICATION
    );
},

调试模式

在调试模式下(app.debug 为 true),异常会返回更多信息,包括:

  • 异常发生的文件路径
  • 异常发生的具体行号
  • 异常堆栈跟踪信息
  • 异常代码
if ($debug) {
    $data += [
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => $e->getTrace(),
        'code' => $e->getCode(),
    ];
}

CORS 支持

异常处理器会自动添加 CORS 头部,确保跨域请求能够正常处理错误响应: