1 回答

TA貢獻1836條經驗 獲得超13個贊
是的,Symfony 已經為此提供了一個集成的解決方案,事實上,Symfony 從根本上捕獲了每個異常并讓您管理它們。
怎么做
首先,編輯config/packages/framework.yaml
并設置一個控制器來管理所有異常(屬性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
當拋出異常時,該控制器將獲取初始請求和拋出的異常作為輸入。這是一個例子:
<?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) {
- 1 回答
- 0 關注
- 110 瀏覽
添加回答
舉報