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

webkenny's avatar

API Error Design Pattern/Best Practice

Hoping to get a nudge of best practices advice. I saw a great post that touched on this a bit but I have a broader use case because not all errors returned by the API are necessarily validation errors on a model field.

My business rules are relatively simple:

  1. Only a single error should be returned to prevent further controller interaction In other words, stop processing or exit out immediately after an error occurs. In Phil's book on APIs he phrases this as:

Try A, get error 1. Try B, get error 2. Try C, it works!

  1. An error follows a simple JSON format. Note code below is different than the HTTP Status code I'll return as well.
{ 
"error":
  {
  "type": "SomeErrorType",
  "code": "ERR-01234",
  "message": "Some error message for the developer",
  "documentation_url" : "http://docs.example.com/errors/ERR-01234"
  }
}
  1. Sometimes I'll use Validator to trap errors (in the event of models) and sometimes they will be custom logic based on my application's needs.

What would be a good way to go about this so it's flexible? So far I have an API Controller that I am extending to handle things like transformation, etc. But I'm not sure how to basically route all errors to a single function or helper class that can trap all of my rules.

Has anyone done anything like this before? Thank you for reading this!

0 likes
2 replies
webkenny's avatar

I thought I would add, if this helps, the direction I am leaning is using a ServiceProvider for this. Something like ErrorServiceProvider but, again, my concern is how to route all errors through it. I am still a bit new to Laravel and trying to wrap my head around this.

Please or to participate in this conversation.