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

megaman7's avatar

API Error display

I understand how error handling is supposed to occur for regular http calls.

Laravel has custom ways to handle specific error types and you can extend this by adding conditional logic to the App\Exceptions\Handler class which can detect errors based on anything you like (i have used error class type, route name and error message) In addition you can set a 404.blade.php file which will be used whenever there is a 404 status code (unless your conditional logic previously mentioned returns before laravel gets this far)

What is the best way to handle errors which are generated by an API?

currently i have conditional logic which detects any error other than a NotFoundHttpException (so i do not override the 404 behavior) and return a custom view. The API does return an error message but i do not display this on the custom error page because it may contain info i dont want a user to see.

Is my current way an acceptable way or can laravel handle this in some other way.

0 likes
3 replies
monooso's avatar

One alternative is to raise custom exceptions for your API endpoints, and then handle them in App\Exceptions\Handler. An ApiResourceNotFoundException, for example. That's usually how I approach it for larger applications.

If it's something a bit simpler, you could get away with some conditional checks in the handler—if it's a JSON (API) request do A, otherwise do B.

megaman7's avatar

@MONOOSO - do you mean something like having a status field in every API response which when an error is generated by the API has its value set to 'error'

Then somewhere in the project consuming the API having code which throws an error if {'status' => 'error'} is detected? preferably throw a custom error to distinguish it from other errors and maybe make sure the API always provides error message, code, trace ect

Is there a place i could put such logic, other than middleware, which would cause it to run for every route.

monooso's avatar

Sorry for the slow response, apparently I don't receive notification of any replies.

In answer to your question, no, that's not what I was getting at. I was talking about throwing custom API-specific exceptions in your code, when an error occurs.

You can then catch those specific exceptions in the Handler class (as you would normally), and return an appropriate (presumably JSON) response.

Stephen

Please or to participate in this conversation.