【问题标题】:Custom exception handler not outputting自定义异常处理程序不输出
【发布时间】: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;

标签: laravel api


【解决方案1】:

我想通了。出于某种原因,当模型不适用于异常消息时,它会显示为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);
}

【讨论】:

    猜你喜欢
    • 2011-07-13
    • 2015-10-18
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多