如何在 laravel 8 中注册自定义异常处理程序
How to register custom exception handler in laravel 8
在 Laravel 7 中,这段代码工作正常。使用 renderable
方法也适用于 laravel 8。但是我不确定在创建 CustomException
class.
后如何在 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);
});
}
在 Laravel 7 中,这段代码工作正常。使用 renderable
方法也适用于 laravel 8。但是我不确定在创建 CustomException
class.
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);
});
}