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

clat23's avatar

Handling errors from an outside API

I have a model that sends requests to an outside API. When this outside API is unable to process the request, it responds with a failure along with an error code and an error message.

My model checks the response for these failures and then throws an exception with a generic message. My controller then catches this exception and flashes that generic message to the user.

I would like to handle each failure depending on the error code that is returned. (i.e. if the app receives error code "12345" then the app flashes "This sample error message" to the user. If the app receives error code "54321", then the app redirects to a specific view).

The most basic way I have in mind to accomplish this is to use a switch statement and write the logic depending on the "case" (error code). However, this outside API has hundreds of different types of error codes, so this can make my model messy really quick.

So my next thought was to create a helper class or a helper function to remove all of this logic from my model. But is this really the cleanest way to do it?

What is the right way to handle this? Does Laravel offer anything for this situation? Any help is appreciated...

0 likes
1 reply
tekmi's avatar
tekmi
Best Answer
Level 23

Instead of using one big switch statement, I would rather create a class like ResponseErrorHandler which would encapsulate the logic related to error codes.

This class could implement magic php methods __get or __call, so that in your exception handler you may bring it to life like:

(new ResponseErrorsHandler)->54321;
(new ResponseErrorsHandler)->12345;

or

(new ResponseErrorsHandler)->54321();
(new ResponseErrorsHandler)->12345();

Thanks to this magic methods, your class by default would catch all the current and future error codes from this external API.

In case a particular code like 54321 or 12345 is important to you, you could create public methods like processCode54321 or processCode12345 and react accordingly there.

Another idea would be to create a separate class for each error code returned from this outside API. Then you would instantiate the proper class in your exception handler, trying to map the error code to the proper class name - however in my opinion this sounds like an over-engineered solution.

If any other solution comes to my mind, I will share it promptly with you.

Good luck!

Please or to participate in this conversation.