Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

wingleee's avatar

Best way to handle error responses for API?

I'm trying to make an application using Laravel and ReactJS, and I'm wondering what's the best way to go about creating error responses? I want all errors to return in a similar json response so that I can handle them all the same on the front end.

Right now I have a login api route, and it gives a validation error. I know how to override the default response, but I want to know what's the best way to override all responses that generate errors. That way i could send it in a format similar to the following:

response: {
    status: 422,
    error: {
        type: "password_incorrect"
    }
}
0 likes
4 replies
nlmenke's avatar

This is typically how I structure my error responses for API calls (though this is just a basic 500 error):

try {
    // logic that may throw an error
} catch (Exception $e) {
    return JsonResponse::create([
        'message' => '500_message',
        'errors' => (object)[
            $e->getCode() => [$e->getMessage()],
        ],
    ], Response::HTTP_INTERNAL_SERVER_ERROR, [
        'Content-Language' => $this->currentLocale,
    ]);
}

I think a 400 error code would be better suited for a validation error.

1 like
wingleee's avatar

Thanks for the response!

That's really similar to how I want to structure my api responses. What I'm looking for is a way to catch all errors and format the api responses the same way so it's easier to consume.

jenky's avatar

take a look at Illuminate/Foundation/Exceptions/Handler.php it had lots of methods that you can overwrite in yourapp/Exceptions/Handler.php

1 like

Please or to participate in this conversation.