gpt4 book ai didi

php - 在根处捕获异常

转载 作者:行者123 更新时间:2023-12-04 09:03:44 26 4
gpt4 key购买 nike

我正在学习 Symfony5,我想知道是否有可能在路由执行后捕获异常。
主要思想是在我的 route 摆脱一些反复出现的 try-catch 代码块:

    public function getStudentMean(int $studentId): Response
{
try {
$mean = $this->gradedStudentService->getMean($studentId);
return new Response($mean, Response::HTTP_OK);
} catch (AbstractApiException $e) {
return $this->returnBadRequestResponse($e->getMessage());
}
}

public function deleteStudent(int $id): Response
{
try {
$this->studentService->deleteStudent($id);
return new Response('', Response::HTTP_NO_CONTENT);
} catch (AbstractApiException $e) {
return $this->returnBadRequestResponse($e->getMessage());
}
}
我是否必须编辑我的 public\index.php文件在这里捕获异常?还有另一种更清洁的方法吗?
谢谢!

最佳答案

是的,Symfony 已经为此提供了一个集成的解决方案,事实上,Symfony 在根目录下捕获每个异常并让您管理它们。
您可以找到信息here .
怎么做
一、编辑config/packages/framework.yaml并设置一个 Controller 来管理所有异常(属性 error_controller )。

framework:
secret: '%env(APP_SECRET)%'
#csrf_protection: true
#http_method_override: true

# Enables session support. Note that the session will ONLY be started if you read or write from it.
# Remove or comment this section to explicitly disable session support.
session:
handler_id: null
cookie_secure: auto
cookie_samesite: lax

#esi: true
#fragments: true
php_errors:
log: true

error_controller: App\Controller\ErrorController::showAction
当抛出异常时,该 Controller 将获取初始请求和抛出的异常作为输入。这是一个例子:
<?php
namespace App\Controller;

use App\Exceptions\ExpiredLinkException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

/**
* Controller for exceptions
*/
class ErrorController extends AbstractCustomController
{

/**
* @param Request $request
* @param Throwable $exception
* @return Mixed
* @throws Throwable
*/
public function showAction(Request $request, Throwable $exception)
{
if ($exception instanceof HttpException) {
if ($exception->getStatusCode() == Response::HTTP_UNAUTHORIZED) {
return new RedirectResponse($_ENV['WEBSITE_BASE_URL'] . 'login?source=' . urlencode($request->getUri()));
}
}
if ($exception instanceof ExpiredLinkException) {
return $this->render('error/expired.html.twig');
}
if ($_ENV["APP_ENV"] == "prod") {
if ($exception instanceof HttpException) {
if ($exception->getStatusCode() == Response::HTTP_FORBIDDEN) {
return $this->render('error/403.html.twig');
}
if ($exception->getStatusCode() == Response::HTTP_NOT_FOUND) {
return $this->render('error/404.html.twig');
}
}
return $this->render('error/500.html.twig');
}
throw $exception;
}
}

关于php - 在根处捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63504225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com