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

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

如何將錯誤處理傳遞給 PHP 中的函數?

如何將錯誤處理傳遞給 PHP 中的函數?

PHP
慕雪6442864 2023-07-01 15:22:40
我需要在 Laravel 項目中的 PHP 類的許多地方處理多種類型的錯誤,當然我不想在代碼中到處重復錯誤處理代碼。我現在有這個代碼:class MyAwesomeClass {    public function parseItems(Request $request) {        // do something        try {            // ...        } catch (Exception $error) {            $this->handleError($error);        }    }    public function handleError(Exception $error) {        $type = get_class($error);        switch ($type) {            case 'TypeAException':                return response([                    'message' => 'My custom message for Type A error',                    'status' => 'Error',                    'errors' => []                ], 500);            case 'TypeBException':                return response([                    'message' => 'My custom message for Type B error',                    'status' => 'Error',                    'errors' => []                ], 500);            default:                // ...                break;        }    }}但該handleError()方法沒有被調用。如何將異常傳遞給 PHP 中的錯誤處理程序方法?
查看完整描述

1 回答

?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

在 Laravel 中,已經為您配置了錯誤和異常處理。無需使用自定義類來實現此目的。


所有異常均由該類處理App\Exceptions\Handler,您可以在該類上自定義方法report:render


/**

?* Render an exception into an HTTP response.

?*

?* @param? \Illuminate\Http\Request? $request

?* @param? \Throwable? $exception

?* @return \Illuminate\Http\Response

?*/

public function render($request, Throwable $exception)

{

? ? if ($exception instanceof TypeAException) {

? ? ? ? return response([

? ? ? ? ? ? 'message' => 'My custom message for Type A error',

? ? ? ? ? ? 'status' => 'Error',

? ? ? ? ? ? 'errors' => []

? ? ? ? ], 500);

? ? }

? ? else if ($exception instanceof TypeBException) {

? ? ? ? return response([

? ? ? ? ? ? 'message' => 'My custom message for Type B error',

? ? ? ? ? ? 'status' => 'Error',

? ? ? ? ? ? 'errors' => []

? ? ? ? ], 500);

? ? }


? ? return parent::render($request, $exception);

}

查看完整回答
反對 回復 2023-07-01
  • 1 回答
  • 0 關注
  • 124 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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