亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在根處捕獲異常

在根處捕獲異常

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 關注
  • 110 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號