为了账号安全,请及时绑定邮箱和手机立即绑定

在根处捕获异常

在根处捕获异常

PHP
绝地无双 2023-10-21 10:04:11
我正在学习 Symfony5,我想知道是否可以在路由执行后捕获异常。主要思想是摆脱我的路线中一些重复的 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文件才能捕获此处的异常?还有另一种更清洁的方法吗?谢谢!
查看完整描述

1 回答

?
开心每一天1111

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) {


查看完整回答
反对 回复 2023-10-21
  • 1 回答
  • 0 关注
  • 59 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信