首页 > 解决方案 > 如何将错误处理传递给 PHP 中的函数?

问题描述

我需要在我的 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 中的错误处理程序方法?

标签: phplaravelerror-handling

解决方案


在 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 文档上的错误处理。


推荐阅读