【问题标题】:How to pass error handling to a function in PHP?如何将错误处理传递给 PHP 中的函数?
【发布时间】:2020-06-27 08:39:25
【问题描述】:

我需要在我的 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 中将异常传递给我的错误处理程序方法?

【问题讨论】:

    标签: php laravel error-handling


    【解决方案1】:

    在 Laravel 中,已经为您配置了错误和异常处理。无需使用自定义类来实现这一点。

    所有异常都由App\Exceptions\Handler类处理,你可以在这个类上自定义reportrender方法:

    /**
     * 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);
    }
    

    有关更多信息,请参阅 Laravel 文档上的 Error Handling

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多