当我得到这个错误时:
Connection.php第620行中的QueryException:SQLSTATE[23000]:完整性违反约束:1062重复条目
我可以用我自己的flash错误消息而不是来处理它吗
哎呀,好像出了问题
有两种方法可以处理异常并显示自定义响应:
1)让框架为您处理它们:
如果你不自己处理异常,Laravel会在类中处理它们:
App'Exceptions'Handler
在render
方法中,您可以截取框架上升的所有异常的呈现。因此,如果你想在出现特定异常时做一些特别的事情,你可以这样修改这个方法:
public function render($request, Exception $e)
{
//check the type of the exception you are interested at
if ($e instanceof QueryException) {
//do wathever you want, for example returining a specific view
return response()->view('my.error.view', [], 500);
}
return parent::render($request, $e);
}
2)自行处理异常:
您可以使用try-catch
块自行处理异常。例如,在控制器的方法中:
try
{
//code that will raise exceptions
}
//catch specific exception....
catch(QueryException $e)
{
//...and do whatever you want
return response()->view('my.error.view', [], 500);
}
这两种情况之间的主要区别在于,在情况1中,您定义了一种通用的、应用程序范围的方法来处理特定的异常。
另一方面,在情况2中,您可以在应用程序
这是我的好
if ($e instanceof 'PDOException) {
$dbCode = trim($e->getCode());
//Codes specific to mysql errors
switch ($dbCode)
{
case 23000:
$errorMessage = 'my 2300 error message ';
break;
default:
$errorMessage = 'database invalid';
}
return redirect()->back()->with('message',"$errorMessage");
}