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 关注
- 91 浏览
添加回答
举报