php - 如何将错误处理传递给 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 中的错误处理程序方法?
解决方案
在 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);
}
有关更多信息,请参阅Laravel 文档上的错误处理。
推荐阅读
- android - Kotlin:启用proguard后应用程序崩溃
- c++ - Omnet++ 中的 .vec 和 .sca 输出有什么区别?
- c# - 在 InitializeComponent 之后未初始化 UWP 绑定
- javascript - ANTLR:遍历 if/elseif/else javascript
- spring-boot - 为外部系统发布 Swagger 文件
- javascript - 如何在 React js 中的模板文字内调用 onclick 函数
- azure - 是否可以查看 Azure 应用服务的重启历史记录?
- javascript - Ajax 不适用于 .htaccess 重写
- php - php can't get the POST data
- python - 如何绘制随机森林的误差和树大小