Skip to content

Conversation

@chuoke
Copy link
Contributor

@chuoke chuoke commented Sep 11, 2025

We may customize the response class, but the exception handler does not use the factory method of the response class, which results in it being unable to use the custom response class.

Edit: add use case

For example, we customized the JSON response like this:

$this->app->singleton(ResponseFactoryContract::class, function ($app) {
            return new class($app['view'], $app['redirect']) extends ResponseFactory
            {
                public function json($data = [], $status = 200, array $headers = [], $options = 0)
                {
                    $msg = $data['message'] ?? $data['msg'] ?? null;
                    if ($msg) {
                        unset($data['message']);
                        $wrapData = [
                            'msg' => $msg,
                            'success' => $status >= 200 && $status < 300,
                        ] + $data;
                    } else {
                        $wrapData = [
                            'msg' => 'success',
                            'success' => true,
                            'data' => $data,
                        ];
                    }

                    return new JsonResponse($wrapData, 200, $headers, $options);
                }
            };
        });

Before PR, the exception response:

{
    "message": "Server Error"
}

We can see that did not use our customized JSON format.

We have 3 ways to maintain consistency.

  • Customize the exception handler response
  • Enable prepareJsonResponse support callbak like shouldReturnJson method
  • Make exception handler use response factory (Accept this PR)

After PR:

{
    "msg": "Server Error",
    "success": false
}

@chuoke chuoke changed the title feat: Support custom response classes without modifying the exception handler [12.x]feat: Support custom response classes without modifying the exception handler Sep 11, 2025
@taylorotwell
Copy link
Member

Can you provide more information on the use case?

@chuoke
Copy link
Contributor Author

chuoke commented Sep 13, 2025

@taylorotwell Thank you for the feedback.

Currently, Laravel creates JSON exception responses by directly instantiating new JsonResponse().
This bypasses the ResponseFactory, which makes it hard to globally enforce a consistent JSON format across both normal and error responses.

I know it’s possible to override the exception handler, but if exception responses were created via the factory as well, it would allow applications to centralize their formatting logic instead of duplicating it. Wouldn’t this improve consistency without affecting existing behavior?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants