nycu-csit / laravel-restful-utils

This package provides utilities for building a restful API for Laravel projects.
MIT License
1 stars 0 forks source link

improvement: exception handler should respond JSON on API endpoint #1

Open zhshize opened 1 week ago

zhshize commented 1 week ago

In Laravel ExceptionHandler, the function shouldReturnJson() determines whether generate JSON response by Accept header.

But, sometimes the client may forget add Accept: application/json, if the request is successful, server responds JSON normally, But if the request is failed (4xx, 5xx), the server responds a webpage.

Obviously, when the endpoint is an API endpoint, to respond a webpage doesn't make sense.

So, just check current route is an API endpoint and respond JSON.

zhshize commented 6 days ago

Laravel 11.x provides Rendering Exceptions as JSON

zhshize commented 6 days ago

Possible solutions:

  1. Laravel 11.x Rendering Exceptions as JSON this issue won't fix on laravel-restful-utils, downstream developer must update bootstrap/app.php for each laravel project

  2. Override shouldReturnJson() in src/Exceptions/Handler.php detect the current route's middleware group's name "api". Downstream developer just update their laravel-restful-utils