[英]How to catch SQL Exception in Laravel 5
干草我正在创建这样的代码:
\Log::info("saving log....");
try{
$data = AstronautCandidateLog::insert($request->logs);
}catch (SQLException $e)
{
\Log::info("SQL Exception happened");
}catch (Exception $e)
{
\Log::info("Exception happened");
}
\Log::info("status save data : ". $data);
但是似乎我的Exception从未被击中。 那么,当sql查询出现问题时,如何在laravel中捕获异常?
提前致谢。
尝试这个
try {
//Your code
} catch(\Illuminate\Database\QueryException $ex){
dd($ex->getMessage());
}
要么
use Illuminate\Database\QueryException;
try {
//Your code
} catch(QueryException $ex){
dd($ex->getMessage());
}
我的情况:在Exception类之前添加\\,否则无法处理
try
{
//write your codes here
}
catch(\Exception $e) {
Log::error($e->getMessage());
}
确保在控制器中使用异常库。 从那里您可以:
try{
Some queries . . .
}catch(Exception $e){
return response()->json([
'error' => 'Cannot excecute query',
],422);
}
要在Laravel中实现异常,只需在控制器顶部添加Exception类即可,
Use Exception;
然后使用try-catch语句包装您希望捕获异常的代码行
try
{
//write your codes here
}
catch(Exception $e)
{
dd($e->getMessage());
}
您也可以以json格式返回错误,以防您正在发出Ajax请求,这一次,请记住在控制器顶部包括Response类。
Use Response;
Use Exception;
然后将您的代码包装在try-catch语句中,如下所示
try
{
//write your codes here
}
catch(Exception $e)
{
return response()->json(array('message' =>$e->getMessage()));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.