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

如何将错误处理传递给 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 关注
  • 72 浏览

添加回答

举报

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