Laravel - Turn Exceptions Into API Responses
Quick / Basic Solution
One can simply edit the exception handler by going to:
Within there, there is a register()
method which registers your renderable and reportable exceptions .
One can put in a switch with a case for each Exception that you wish to turn into a legitimate API response like so:
A Better Solution
It won't take long with the previous method, before your Handler gets absolutely filled with lots of exceptions and looks quite ugly and unmanageable. It would be a lot nicer if we could just "register" the exceptions automatically, so we never have to touch this code again and have all of the logic that handles the rendering in the Exceptions themselves.
Luckily, this is as easy as adding a render()
method to our exceptions as explained here.
For this, I create an abstract exception called AbstractRenderableException
that my other exceptions extend like so:
This allows me to create self-explanatory exceptions like so:
Now in my request handlers, I can simply do:
First published: 11th August 2022