在 laravel 12 中,当应用抛出未捕获的异常导致 500 错误时,核心处理逻辑位于 app\exceptions\handler 类。通过重写 register() 方法注册自定义异常映射,或在 render() 方法中拦截特定异常并返回自定义响应,即可将默认的调试页面替换为友好的错误提示或 json 数据。

register() 如何映射异常到 HTTP 状态码?
使用 register() 方法可以将特定的异常类绑定到对应的 HTTP 状态码,从而让框架在渲染前自动调整响应状态。例如,将 NotFoundHttpException 映射为 404,或将自定义的业务异常映射为 422。这种方式适合全局性的状态码修正,无需在控制器中手动抛出带有状态码的异常。

namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Validation\ValidationException;
class Handler extends Handler
{
public function register(): void
{
$this->reportable(function (Throwable $e) {
// 默认报告逻辑
});
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->expectsJson()) {
return response()->json([
'message' => 'Resource not found',
'status' => 404
], 404);
}
});
$this->map(ValidationException::class, function ($ex) {
return response()->json([
'errors' => $ex->errors(),
'message' => 'Validation failed'
], 422);
});
}
}
上述代码展示了如何在 register 中使用 map 和 renderable。对于 JSON 请求,NotFound 会返回 JSON;对于验证异常,直接返回 422 状态码及错误详情。这避免了在每个控制器中重复编写验证响应逻辑。
render() 如何拦截特定业务异常?
当需要针对特定的业务逻辑异常(如余额不足、权限拒绝)返回不同的前端视图或 JSON 结构时,应在 render() 方法中进行拦截。Laravel 12 依然保留了基于类的类型提示匹配机制,可以直接在 render 签名中指定异常类型,实现细粒度的控制。
Laravel Cloud(cloud.laravel.com)。此技能用于处理所有 Laravel Cloud 请求,包括搜索和读取数据。只要任务涉及 Laravel Cloud,即使用此技能。

namespace App\Exceptions;
use App\Exceptions\InsufficientBalanceException;
use Illuminate\Foundation\Exceptions\Handler;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\HttpException;
class Handler extends Handler
{
public function render($request, Throwable $exception): \Illuminate\Http\Response|\Illuminate\Responses\JsonResponse|\Symfony\Component\HttpFoundation\Response
{
if ($exception instanceof InsufficientBalanceException) {
Log::error('Insufficient balance', ['user_id' => auth()->id()]);
if ($request->wantsJson()) {
return response()->json([
'error' => 'INSUFFICIENT_FUNDS',
'message' => $exception->getMessage()
], 402);
}
return redirect()->back()->with('error', $exception->getMessage());
}
return parent::render($request, $exception);
}
}
这段代码演示了如何拦截 InsufficientBalanceException。如果客户端期望 JSON,则返回 402 状态码和错误信息;如果是网页请求,则重定向回上一页并携带 Flash 消息。这种处理方式确保了 API 和 Web 端都能获得合适的错误反馈,同时记录了关键日志。
自定义异常类如何定义与触发?
为了使 Handler 中的拦截逻辑生效,必须创建具体的自定义异常类。这些类通常继承自 Exception 或 HttpException,并在业务逻辑中通过 throw 语句主动抛出。Laravel 12 要求异常类遵循 PSR-4 自动加载规范,确保命名空间正确。
namespace App\Exceptions;
use Exception;
class InsufficientBalanceException extends Exception
{
protected $message = 'Account balance is insufficient.';
protected $code = 402;
public function __construct(string $message = '', int $code = 0, Exception $previous = null)
{
parent::__construct($message ?: $this->message, $code, $previous);
}
}
在业务代码中,只需实例化并抛出该异常:throw new InsufficientBalanceException('Current balance: $5.00');。框架会自动将其传递给 Handler::render() 进行统一处理,从而实现关注点分离。










