我正在尝试为我的API输出自定义异常:
app / Exceptions / Handler.php
public function render($request, Throwable $exception)
{
if ($exception instanceof \Stripe\Exception\ApiErrorException) {
return response()->json([
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
$response = $this->handleException($request, $exception);
return $response;
}
public function handleException($request, Exception $exception)
{
if ($exception instanceof MethodNotAllowedHttpException) {
return $this->errorResponse('The specified method for the request is invalid', 405);
}
if ($exception instanceof NotFoundHttpException) {
//return $this->errorResponse('The specified URL cannot be found', 404);
dd('woo');
}
if ($exception instanceof HttpException) {
return $this->errorResponse($exception->getMessage(), $exception->getStatusCode());
}
if (config('app.debug')) {
return parent::render($request, $exception);
}
return $this->errorResponse('Unexpected Exception. Try later', 500);
}
现在,我正在尝试通过查询控制器中不存在的ID来测试异常处理程序:
public function processCheckout(Request $request)
{
//Id 100 doesn't exist
$plan = Plan::findOrFail(100);
$user = $user = auth()->user();
//If user has no subscriptions subscribe them to new plan
if($user->subscriptions->count() === 0){
$user->newSubscription($plan->name, $plan->stripe_plan_id)->create($request->payment_method['id']);
//return response([], 201);
}
}
我没有把laravel抛出异常放在处理程序中,而是一直没有异常发生。当我打开调试时,render方法似乎没有捕获到异常:
{
"message": "No query results for model [App\\Plan] 100",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
}
如何使它工作并实现自己的自定义消息?这是:
if ($exception instanceof NotFoundHttpException) {
//return $this->errorResponse('The specified URL cannot be found', 404);
dd('woo');
}
答案 0 :(得分:0)
我知道了。由于某种原因,当模型不用于异常时,消息会指出它是NotFoundHttpException
。如您在以上响应的这一部分中所见:
{
"message": "No query results for model [App\\Plan] 100",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
}
真正的异常是未找到模型异常:
在顶部
use Illuminate\Database\Eloquent\ModelNotFoundException;
在渲染方法中
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'message' => 'Entry for '.str_replace('App\\', '', $exception->getModel()).' not found'], 404);
}