MarcinOrlowski / laravel-api-response-builder

Builds nice, normalized and easy to consume REST JSON responses for Laravel powered APIs.
MIT License
721 stars 79 forks source link

How does ExceptionHandlerHelper return information in a custom format? #243

Open ecfxs opened 1 year ago

ecfxs commented 1 year ago

Steps to reproduce the behavior:

I defined a app/Http/Response/RB.php image

And used ExceptionHandlerHelper How can I return the error message in the RB format I defined?

This is the default format image

This is not the format I want

Thank you

Environment

TheCoderRaman commented 9 months ago

Hi @ecfxs ,

The quick fix for you is to edit App\Exceptions\Handler.php

Incase: You are not doing exception handling with Response Builder See Exception Handling for reference for using Response Builder exception handler.

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register(): void
    {
        $this->renderable(function (Throwable $ex, $request) {
            return ExceptionHandlerHelper::handle($ex, $request);
        });
    }

Next, update the register method as follows

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register(): void
    {
        $this->renderable(function (\Throwable $ex, $request) {
            $response = ExceptionHandlerHelper::render($request, $ex);

            // Get response data from json response
            $data = $response->getData(true);

            // Modify the response format as needed
            $date = new \DateTime();
            $data['timezone'] = $date->getTimezone();
            $data['timestamp'] = $date->getTimestamp();

            // Update the json response with new data
            $response->setData($data);

            return $response;
        });
    }

The process involves

Rendering the response using ExceptionHandlerHelper followed by modifying the rendered response data as necessary, and subsequently updating the response with the new data.