>厭倦了自定義中間件,以強迫JSON響應laravel中的API例外嗎? Laravel 11簡化了此過程。 這種方法消除了對這樣的中間件的需求:
>class ForceJsonResponse { public function handle(Request $request, Closure $next) { $request->headers->set('Accept', 'application/json'); return $next($request); } }
現在,您可以在應用程序配置中直接達到相同的結果:
// bootstrap/app.php return Application::configure(basePath: dirname(__DIR__)) //... ->withExceptions(function (Exceptions $exceptions) { $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) { return $request->is('api/*'); }); })->create();這個簡潔的代碼,利用
的方法,確保API路由(shouldRenderJsonWhen()
)中的所有例外都被渲染為JSON,而不論api/*
Accept
header如何。 請記住,您仍然需要處理非錯誤響應,以確保他們還返回JSON。
以上是始終呈現API例外作為JSON在Laravel中的詳細內容。更多資訊請關注PHP中文網其他相關文章!