如何普遍处理 Laravel 中某个 属性 的异常?
How can I universally handle an exception with a certain property in Laravel?
我想创建类似于
中的 unauthenticated() 函数的东西
app\Exceptions\Handler.php
但我的异常是由 Guzzle 生成的,其中包含特定的 http 代码和 json 正文。
我已经有一个助手 class 可以像这样工作:
public static function get($enum) {
$headers = self::headers();
$client = new Client();
try {
$response = $client->request('GET', config('app.apiurl') . '/api/' . $enum, ['headers' => $headers]);
} catch (\Exception $e) {
$response = $e->getResponse();
$body = json_decode($response->getBody(), true);
$code = $response->getStatusCode();
if ($body['code'] == 101 && $code == 412) {
throw new \Exception("wizard eerst", 101);
}
}
但我更喜欢在通用处理程序中执行此操作,例如某种异常中间件。所以我不想在每次调用时都使用 try catch,而是捕获所有符合我的描述的异常并通过重定向处理它们。
解决方案
public function render($request, Exception $exception) {
$response = $exception->getResponse();
$body = json_decode($response->getBody(), true);
$code = $response->getStatusCode();
if ($body['code'] == 101 && $code == 412) {
if ($request->expectsJson()) {
return response()->json(['error' => 'Je moet eerst de profielwizard afmaken'], $code);
}
return redirect('/wizard');
}
return parent::render($request, $exception);
}
app\Exceptions\Handler.php
中存在一个 render
函数。
处理不同类型的Exception,可以尝试:
public function render($request, Exception $e)
{
if ($e instanceof SomeTypeException1)
{
#handle it
}
else if($e instanceof SomeTypeException2)
{
#handle it
}
return parent::render($request, $e);
}
我想创建类似于
中的 unauthenticated() 函数的东西app\Exceptions\Handler.php
但我的异常是由 Guzzle 生成的,其中包含特定的 http 代码和 json 正文。
我已经有一个助手 class 可以像这样工作:
public static function get($enum) {
$headers = self::headers();
$client = new Client();
try {
$response = $client->request('GET', config('app.apiurl') . '/api/' . $enum, ['headers' => $headers]);
} catch (\Exception $e) {
$response = $e->getResponse();
$body = json_decode($response->getBody(), true);
$code = $response->getStatusCode();
if ($body['code'] == 101 && $code == 412) {
throw new \Exception("wizard eerst", 101);
}
}
但我更喜欢在通用处理程序中执行此操作,例如某种异常中间件。所以我不想在每次调用时都使用 try catch,而是捕获所有符合我的描述的异常并通过重定向处理它们。
解决方案
public function render($request, Exception $exception) {
$response = $exception->getResponse();
$body = json_decode($response->getBody(), true);
$code = $response->getStatusCode();
if ($body['code'] == 101 && $code == 412) {
if ($request->expectsJson()) {
return response()->json(['error' => 'Je moet eerst de profielwizard afmaken'], $code);
}
return redirect('/wizard');
}
return parent::render($request, $exception);
}
app\Exceptions\Handler.php
中存在一个 render
函数。
处理不同类型的Exception,可以尝试:
public function render($request, Exception $e)
{
if ($e instanceof SomeTypeException1)
{
#handle it
}
else if($e instanceof SomeTypeException2)
{
#handle it
}
return parent::render($request, $e);
}