You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 11:如何通过自定义类处理API异常并定制响应

Laravel 自定义API异常处理(使用独立类覆盖renderable逻辑)

实现步骤:

1. 创建自定义异常处理类

在app/Exceptions目录下新建CustomExceptionHandler.php,继承Laravel默认的异常处理器,通过renderable方法注册各类异常的响应逻辑:

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Auth\AuthenticationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Routing\Exceptions\RouteNotFoundException;

class CustomExceptionHandler extends ExceptionHandler
{
    /**
     * 注册自定义异常渲染规则
     */
    public function register()
    {
        // 处理表单验证异常
        $this->renderable(function (ValidationException $e, Request $request) {
            return response()->json($e->errors(), Response::HTTP_UNPROCESSABLE_ENTITY);
        });

        // 处理请求方法不允许异常
        $this->renderable(function (MethodNotAllowedHttpException $e, Request $request) {
            $result = [
                'errorMsg' => 'Method not allowed.',
                'body' => ['requestedUrl' => $request->getUri()]
            ];
            return response()->json($result, Response::HTTP_METHOD_NOT_ALLOWED);
        });

        // 处理各类资源未找到异常
        $this->renderable(function ($e, Request $request) {
            if ($e instanceof ModelNotFoundException || $e instanceof NotFoundHttpException || $e instanceof RouteNotFoundException) {
                $result = [
                    'errorMsg' => $e->getMessage() ?? 'Record not found.',
                    'body' => ['requestedUrl' => $request->getUri()]
                ];
                return response()->json($result, Response::HTTP_NOT_FOUND);
            }
        });

        // 处理未授权异常
        $this->renderable(function (AuthenticationException $e, Request $request) {
            $result = [
                'errorMsg' => 'Unauthenticated',
                'body' => ['requestedUrl' => $request->getUri()]
            ];
            return response()->json($result, Response::HTTP_UNAUTHORIZED);
        });

        // 处理通用HTTP异常
        $this->renderable(function (HttpException $e, Request $request) {
            return response()->json($e->getMessage(), $e->getStatusCode());
        });

        // 处理其他未捕获异常
        $this->renderable(function (\Exception $e, Request $request) {
            $result = [
                'errorMsg' => 'Internal server error.',
                'body' => ['requestedUrl' => $request->getUri()],
                'exception' => $e->getMessage()
            ];
            return response()->json($result, Response::HTTP_INTERNAL_SERVER_ERROR);
        });
    }
}

2. 替换默认异常处理器

修改bootstrap/app.php,将Laravel默认的异常处理器替换为我们的自定义类:

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\CustomExceptionHandler::class
);

说明:

  • renderable方法是Laravel提供的用于注册异常自定义响应的接口,通过它可以为不同类型的异常绑定专属的处理逻辑,替代原有的respond闭包写法。
  • 若只需针对API请求处理异常,可以在每个renderable闭包中添加if ($request->is('api/*'))判断,避免影响非API请求的异常响应。
  • 自定义类继承了默认处理器的所有功能,你可以根据需求重写其他方法(如report)来扩展异常日志等功能。

内容的提问来源于stack exchange,提问作者Mehul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 12:17:01