78 lines
3.9 KiB
PHP
78 lines
3.9 KiB
PHP
<?php
|
||
|
||
use App\Enum\ErrorEnum;
|
||
use Illuminate\Foundation\Application;
|
||
use Illuminate\Foundation\Configuration\Exceptions;
|
||
use Illuminate\Foundation\Configuration\Middleware;
|
||
use Illuminate\Support\Facades\Log;
|
||
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
|
||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||
|
||
return Application::configure(basePath: dirname(__DIR__))
|
||
->withRouting(
|
||
web: __DIR__.'/../routes/web.php',
|
||
api: __DIR__.'/../routes/api.php',
|
||
commands: __DIR__.'/../routes/console.php',
|
||
health: '/up',
|
||
)
|
||
->withMiddleware(function (Middleware $middleware) {
|
||
//
|
||
})
|
||
->withExceptions(function (Exceptions $exceptions) {
|
||
$exceptions->render(function (Throwable $e) {
|
||
// 判断异常是否为Exception类型
|
||
if ($e instanceof \Exception) {
|
||
// \App\Models\new\log\ErrorLogModel::create([
|
||
// 'type' => 0,
|
||
// 'content' => json_encode([
|
||
// 'message' => $e->getMessage(),
|
||
// 'line' => $e->getLine(),
|
||
// 'file' => $e->getFile(),
|
||
// 'trace' => $e->getTraceAsString(),
|
||
// ]),
|
||
// 'created_at' => time()
|
||
// ]);
|
||
// 使用switch语句判断异常类型
|
||
switch (true) { // 注意这里使用了 'true' 因为 PHP 不允许在 case 中使用表达式
|
||
// 如果异常是NotFoundHttpException类型
|
||
case $e instanceof NotFoundHttpException:
|
||
// 返回一个自定义的JSON响应,状态码为404,错误信息为"路由未找到"
|
||
return jInstanceof(ErrorEnum::NOT_FOUND, '路由未找到', $e->getMessage());
|
||
|
||
// 如果异常是MethodNotAllowedHttpException类型
|
||
case $e instanceof MethodNotAllowedHttpException:
|
||
Log::error($e->getMessage());
|
||
// 返回一个自定义的JSON响应,状态码为405,错误信息为"请求方式错误"
|
||
return jInstanceof(405, '请求方式错误', $e->getMessage());
|
||
|
||
// 如果异常是UnprocessableEntityHttpException类型
|
||
case $e instanceof UnprocessableEntityHttpException:
|
||
Log::warning($e->getMessage());
|
||
// 返回一个自定义的JSON响应,状态码为422,错误信息为"服务器处理不过来啦"
|
||
return jInstanceof(422, '服务器处理不过来啦', $e->getMessage());
|
||
|
||
// // 如果异常是HttpException类型
|
||
// case $e instanceof HttpException:
|
||
// Log::error($e->getMessage());
|
||
// // 返回一个自定义的JSON响应,状态码为异常的状态码,错误信息为"服务器出错啦"
|
||
// return jInstanceof($e->getCode(), ErrorEnum::FAIL->description(), 'ERROR:'. $e->getMessage());
|
||
//
|
||
// // 对于所有其他类型的异常,默认返回500内部服务器错误
|
||
default:
|
||
Log::critical($e->getMessage()); // 记录更严重的日志级别
|
||
// 返回一个自定义的JSON响应,状态码为500,错误信息为"内部服务器错误"
|
||
return jInstanceof($e->getCode(), $e->getMessage(), $e->getCode());
|
||
}
|
||
}
|
||
|
||
return jInstanceof(ErrorEnum::FAIL, '服务器出错啦~', [
|
||
'message' => $e->getMessage(),
|
||
'code' => $e->getCode(),
|
||
'file' => $e->getFile(),
|
||
'line' => $e->getLine(),
|
||
'trace' => $e->getTrace(),
|
||
]);
|
||
});
|
||
})->create();
|