miCRoSCoPiC_eaRthLinG
miCRoSCoPiC_eaRthLinG

Reputation: 2960

CakePHP 3.x REST API - Custom Error Messages when debug is off

I have an AngularJS-based Single Page Application connected to a CakePHP 3.x backend. CakePHP simply acts like a REST API here.

When debug is turned on in app.php, the error messages thrown via exceptions get returned correctly and can be displayed as meaningful messages in the frontend.
Example: "Password does not match."

However, with debug off, only the default error message associated with the HTTP Status code is returned.
Example: "Internal Server Error"

How can I ensure the full and complete error messages get sent to the frontend?

Thank you.

Upvotes: 0

Views: 512

Answers (1)

ndm
ndm

Reputation: 60463

Use HttpException whenever appropriate

By default CakePHP's exception renderer will only use the exception's message when either debug mode is enabled, or when then exception is of the type \Cake\Http\Exception\HttpException - use it (respectively one of its subclasses provided by the core) whenever appropriate!

For your specific example of an authentication failure for example, you should use a \Cake\Http\Exception\ForbiddenException, which maps to a HTTP 403 error. That is the correct thing to do from an HTTP perspective, and it would also solve your problem with custom messages being swallowed.

See also API > \Cake\Http\Exception\HttpException

Use a custom exception renderer

It's also not uncommon to create custom/extended exception renderers in order to render custom formats for API responses. An example would be if you wanted to submit validation errors, which often come in groups, and even in a nested fashion.

See for example CakePHP 3: Exception handling / serialization in a RESTful API.

Upvotes: 1

Related Questions