我有 homecontroller ,其中有一个功能 storestudent ,它应该能够处理异常,该怎么办?
public function storestudent(Request $request)
{
try
{
$student= new student();
$student->sregno= $request['regno'];
$student->save();
return redirect('/home');
} catch (Exception $e){
throw new Execution;
}
}
try-catch异常不起作用,请帮助我解决此问题。 谢谢。
这是 Execution.php
<?php
namespace App\Exceptions;
use Exception;
class Execution extends Exception
{
//
}
在 handler.php
中 public function report(Exception $exception)
{
if($exception instanceof Execution)
{
echo "invalid register no";
}
parent::report($exception);
}
它给了我这个错误
This page isn’t working 127.0.0.1 is currently unable to handle this request.
HTTP ERROR 500
任何人都可以帮助我显示我的消息,它应该重定向到同一页面。
答案 0 :(得分:0)
在这里尝试捕获,您可以使用Log将记录中的错误保留下来,并且可以在应用程序的log部分中检查记录:
public function storestudent(Request $request)
{
try
{
$student= new student();
$student->sregno= $request['regno'];
$student->save();
return redirect('/home');
} catch(Exception e){
$error = sprintf('[%s],[%d] ERROR:[%s]', __METHOD__, __LINE__, json_encode($e->getMessage(), true);
\Log::error($error);
}
}
有关Log fascade的更多信息,请检查以下链接:Logging。
另一种方法是处理异常自定义异常处理,您可以在此处获得。Error handling
要在重定向中显示错误消息,只需在laravel中使用Flash消息,而无需自定义例外。以下代码:
public function storestudent(Request $request)
{
try
{
$student= new student();
$student->sregno= $request['regno'];
$student->save();
\Session::flash('message','Saved successfully');
return redirect('/home');// if you want to go to home
} catch(Exception e){
\Session::flash('error', 'Unable to process request.Error:'.json_encode($e->getMessage(), true));
}
return redirect()->back(); //If you want to go back
}
Flash消息:
@if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{
Session::get('message') }}</p>
@endif
或更常见的Flash视图:
<div class="flash-message">
@foreach (['danger', 'warning', 'success', 'info','error'] as $msg)
@if(Session::has($msg))
<p class="alert alert-{{ $msg }}">{{ Session::get($msg) }}
</p>
@endif
@endforeach
</div>
控制器代码:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Candidate;
use App\student;
use Exception;
class Homecontroller extends Controller
{
//function for login page
public function insertReg()
{
return view('login');
}
public function storestudent(Request $request)
{
try {
if ( !student::where('sregno',$request->regno )->exists() ) {
$student= new student();
$student->sregno= $request->regno;
if ($student->save()) {
\Session::flash('message','Saved successfully');
return redirect('/home');// if you want to go to home
} else {
throw new Exception('Unable to save record.);
}
} else {
throw new Exception('Record alreasy exists with same sregno');
}
} catch(Exception $e){
\Session::flash('error', 'Unable to process request.Error:'.json_encode($e->getMessage(), true));
}
return redirect()->back(); //If you want to go back
}
希望这会有所帮助。