Red*_*sco 0 php try-catch laravel
当您在数据库中没有要删除的内容时,我尝试显示一条消息,而不是显示一个错误,表明您有一个空值
public function destroy($customer_id)
{
$customer_response = [];
$errormsg = "";
$customer = Customer::find($customer_id);
$result = $customer->delete();
try{
//retrieve page
if ($result){
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
}else{
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);
}catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
}
return Response::json(['errormsg'=>$errormsg]);
}
Run Code Online (Sandbox Code Playgroud)
与我之前的商店功能相比,try/catch 方法不起作用
进一步阅读findOrFail。您可以捕获它在找不到时抛出的异常。
try {
$customer = Customer::findOrFail($customer_id);
} catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
return Response::json(['errormsg'=>$errormsg]);
}
$result = $customer->delete();
if ($result) {
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
} else {
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3389 次 |
| 最近记录: |