猿问

在根处捕获异常

我正在学习 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文件才能捕获此处的异常?还有另一种更清洁的方法吗?


谢谢!


绝地无双
浏览 94回答 1
1回答

开心每一天1111

是的,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当抛出异常时,该控制器将获取初始请求和抛出的异常作为输入。这是一个例子:<?phpnamespace 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) {
随时随地看视频慕课网APP
我要回答