【发布时间】:2020-06-22 17:22:42
【问题描述】:
我正在尝试为我的 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 没有抛出我放在处理程序中的异常,我一直没有得到任何异常。当我打开调试时,渲染方法中似乎没有捕获到异常:
{
"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');
}
【问题讨论】:
-
你导入
NotFoundHttpException了吗? -
是的,我有:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;