我使用的是Laravel 5.5,我希望处理来自自定义处理程序的自定义异常,而不是来自app\Exceptions\Handler.php
。现在,如果某个字段在用户提交的表单中为空,我会发现异常。它的完美结合是这样的:
ProfileController.php :
public function update(Request $request, $id){
$this->guzzleService->put(
$request,
ApiEndPoints::UPDATE_PROFILE . $id,
true
);
return back()->with('SavedCorrectly', 'Changes saved correctly');
}
应用\例外\ Handler.php
public function render($request, Exception $exception)
{
if($exception instanceof ClientException && $exception->getCode() == 422)
return back()->withErrors(
json_decode((string) $exception->getResponse()->getBody(), TRUE)["errors"]
);
return parent::render($request, $exception);
}
问题在于我想重构它,所以它仍然是这样的:
ProfileController.php
public function update(Request $request, $id){
try {
$this->guzzleService->put(
$request,
ApiEndPoints::UPDATE_PROFILE . $id,
true
);
return back()->with('SavedCorrectly', 'Cambios guardados correctamente');
} catch(ClientException $exception) {
if ($exception->getCode() == 500) throw new InternalServerErrorException;
if ($exception->getCode() == 422) throw new UnprocessableEntityException;
}
}
应用\例外\ HttpExceptions \ UnprocessableEntityException.php
<?php
namespace App\Exceptions\HttpExceptions;
use GuzzleHttp\Exception\ClientException;
class UnprocessableEntityException extends \Exception
{
public function render($request, ClientException $exception)
{
return back()->withErrors(
json_decode((string) $exception->getResponse()->getBody(), TRUE)["errors"]
);
}
}
但是我收到了这个错误:
类型错误:参数2传递给 应用程序\例外\ HttpExceptions \ UnprocessableEntityException ::渲染() 必须是GuzzleHttp \ Exception \ ClientException的实例,无 给予,召唤 ... \ vendor \ laravel \ framework \ src \ Illuminate \ Foundation \ Exceptions \ Handler.php 在第169行
答案 0 :(得分:1)
这是因为你传递了一个新的异常
public function update(Request $request, $id){
try {
$this->guzzleService->put(
$request,
ApiEndPoints::UPDATE_PROFILE . $id,
true
);
return back()->with('SavedCorrectly', 'Cambios guardados correctamente');
} catch(ClientException $exception) {
if ($exception->getCode() == 500) throw new InternalServerErrorException((string) $exception->getResponse()->getBody());
if ($exception->getCode() == 422) throw new UnprocessableEntityException((string) $exception->getResponse()->getBody());
}
}
和
<?php
namespace App\Exceptions\HttpExceptions;
use GuzzleHttp\Exception\ClientException;
class UnprocessableEntityException extends \Exception
{
public function render($request)
{
return back()->withErrors(
json_decode((string) $this->message, TRUE)["errors"]
);
}
}