问题描述
在Laravel 7中,此代码可以正常工作。在Laravel 8中也可以使用renderable
方法。但是,我不确定在创建CustomException
类之后如何在laravel 8中注册它。
public function render($request,Exception $exception)
{
if ($exception instanceof ValidationException) {
if ($request->expectsJson()) {
return response('Sorry,validation failed.',422);
}
}
return parent::render($request,$exception);
}
解决方法
文档也让我有些困惑。试试这个:
public function register()
{
$this->renderable(function (ValidationException $e,$request) {
if ($request->expectsJson()) {
return response('Sorry,validation failed.',422);
}
});
}
,
这对我有用。
注册方法
public function register()
{
$this->renderable(function(Exception $e,$request) {
return $this->handleException($request,$e);
});
}
handleException的内容
public function handleException($request,Exception $exception)
{
if($exception instanceof RouteNotFoundException) {
return response('The specified URL cannot be found.',404);
}
}
希望您会发现它有用。
,我在 Laravel 8 上使用这个
public function register()
{
$this->reportable(function (Throwable $e) {
});
$this->renderable(function (Throwable $e) {
return $this->handleException($e);
});
}
来源: https://tony-stark.medium.com/laravel-8-error-handling-upgraded-2021-1ea9afcc2e95
,试试这个
public function register()
{
$this->renderable(function(\Illuminate\Validation\ValidationException $e,$request) {
return response()->json([
'result' => 1,'errors' => $e->errors()
],200);
});
}