When I started working with RESTful services in PHP, return API error messages to browser was always an issue, basically because must of the time you have to return the same error from different controllers, which leads to code duplication, error description differences and many other problems.
So I decided to create this Laravel package to make error handling as easy as possible.
Name: esdlabs/reply
Author: Victor Cruz
URL: https://github.com/esdlabs/reply
Features:
- Pre-defined errors and response codes
- Run time errors response
- Errors defined at database
Installation:
Preparation:
Open your composer.json file and add the following to the require array:
1 |
"esdlabs/reply": "1.*" |
Install dependencies
1 |
php composer install |
or
1 |
php composer update |
Integration:
After installing the package, open your Laravel config file app/config/app.php and add the following lines.
In the $providers array add the following service provider for this package.
1 |
'Esdlabs\Reply\ReplyServiceProvider', |
In the $aliases array add the following facade for this package.
1 |
'Reply' => 'Esdlabs\Reply\Facades\Reply', |
Migrations
1 |
php artisan migrate --package=esdlabs/reply |
Database definition:
Table name: reply_errors
- id
- error_code
- response_code
- description
Define your errors at the errors table as follow:
id | error_code | response_ code | description |
---|---|---|---|
1 | 0x001 | 401 | Invalid username or password |
2 | 0x002 | 406 | Validation failed |
Usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class AuthController extends Controller { public function auth() { try { ... } catch (CustomException $e) { return Reply::error('0x001'); } catch (Exception $e) { return Reply::customError('Custom error description', 500); } } } |