Я новичок в Laravel. Я пытаюсь обработать исключения в laravel на Handler.php, выбрасывая исключение из контроллера. Я получаю разные ошибки, пытаясь это, от «Вызова неопределенной функции App \ Http \ Controllers \ render ()», в которой я решил добавить запрос Request $ в методе index (не знаю, возможно ли это и правильно ли это делать ). Также пробовал много разных способов, мой код комментируется в некоторых важных частях, также я пытаюсь сделать ошибку в коде, чтобы проверить, работает ли моя обработка ошибок, вот где начинается моя головная боль и ничего об ошибке погрузочно-разгрузочные работы. Я пытался создать класс централизованной обработки ошибок в Handler.php, чтобы уловка моего метода могла быть проще. Мне нужна помощь, чтобы выяснить мои ошибки, пожалуйста. Спасибо! :)
Я уже пытался исправить всплывающие ошибки, такие как ошибка рендеринга, запрос, и они просто продолжают идти, или моя страница остается пустой без ничего. Также у меня была ошибка, которая говорила, что перенаправление было плохим (я думаю, что сделал бесконечный цикл ошибок перенаправления). У меня есть некоторые попытки прокомментировать код также.
Редактировать: уже решено. сделал также CustomException, так что я могу обрабатывать все исключения, которые я хочу в Controller, и те, которые не включены в try-catch контроллера, будут обрабатываться в Handler.php. Весь загруженный мною код обновляется, и, конечно же, специально для того, чтобы опробовать код, «thow new exception».
Метод индекса на контроллере:
public function index(Request $request)
{
try {
//custom message if this methods throw an exception
\Session::put('errorOrigin', " mostrando los clientes");
throw new \App\Exceptions\CustomException('customerror');
//throw exception to make tests
//...clients query....
$user_type = Auth::user()->user_type_id;
if($user_type == 1){//admin user
return view('admin.clients.index', compact('clients'));
}
}catch(\App\Exceptions\CustomException $e){
report($e);//report custom exception to laravel error log
$errorOrigin = Illuminate\Http\Request::session()->get('errorOrigin');
\Session::flash('message_type', 'negative');
\Session::flash('message_icon', 'hide');
\Session::flash('message_header', 'Success');
\Session::flash('error', '¡Ha ocurrido un error' . $errorOrigin . "!"
.' Si este persiste contacte al administrador del sistema');
return redirect()->back();//redirecting with error message at session
}
}
метод рендеринга в Handler.php (приложение / исключения)
public function render($request, Exception $exception)
{ $errorOrigin = $request->session()->get('errorOrigin');
//this return is just some trying
//return parent::render($request, $exception);
//return dd($exception);
//return parent::render($request, $exception);
//just in case the error is thrown but not handled ad a try catch, this would handle it.
if($exception instanceof \App\Exceptions\CustomException) {
Session::flash('message_type', 'negative');
Session::flash('message_icon', 'hide');
Session::flash('message_header', 'Success');
Session::flash('error', '¡Ha ocurrido un error ' . $errorOrigin ."!" .' Si este persiste contacte al administrador del sistema');
return redirect()->back();
}
if($exception instanceof \ErrorException) {
Session::flash('message_type', 'negative');
Session::flash('message_icon', 'hide');
Session::flash('message_header', 'Success');
Session::flash('error', '¡Ha ocurrido un error ' . $errorOrigin . "!"
.' Si este persiste contacte al administrador del sistema');
return redirect()->back();
}elseif($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
Session::flash('message_type', 'negative');
Session::flash('message_icon', 'hide');
Session::flash('message_header', 'Success');
Session::flash('error', '¡La página a la que ha intentado
acceder no existe o no es accesible en este momento!');
return back();
}elseif($exception instanceof \Symfony\Component\Debug\Exception\FatalThrowableError) {
Session::flash('message_type', 'negative');
Session::flash('message_icon', 'hide');
Session::flash('message_header', 'Success');
Session::flash('error', '¡Ha ocurrido un error!');
return back();
}elseif($exception instanceof \Illuminate\Auth\AuthenticationException) {
return Redirect::back()->withErrors($validator)->withInput();
}elseif($exception instanceof \UnexpectedValueException) {
Session::flash('message_type', 'negative');
Session::flash('message_icon', 'hide');
Session::flash('message_header', 'Success');
Session::flash('error', '¡Ha ocurrido un error con un valor no válido al ' . $errorOrigin . "!"
.' Si este persiste contacte al administrador del sistema');
return back();
}elseif($exception instanceof \Illuminate\Database\QueryException) {
Session::flash('message_type', 'negative');
Session::flash('message_icon', 'hide');
Session::flash('message_header', 'Success');
Session::flash('error', '¡Ha ocurrido un error en la consulta a la base de datos!'
.' Si este persiste contacte al administrador del sistema');
return back();
}else{/*Original error handling*/
return parent::render($request, $exception);
}
}
Класс пользовательских исключений (пустой)
<?php
namespace App\Exceptions;
use Exception;
class CustomException extends Exception
{
/**
*/
}