ServITech uses a standardized error response format across all API endpoints to ensure consistent error handling on the client side. All errors return structured JSON responses with appropriate HTTP status codes and localized error messages.
return ApiResponse::error( status: Response::HTTP_NOT_FOUND, message: __('messages.common.not_found', ['item' => 'Article']), errors: ['id' => 'Article with this ID does not exist']);
POST /api/auth/registerContent-Type: application/json{ "email": "invalid-email", "password": "123"}
{ "status": 422, "message": "The email field must be a valid email address. (and 1 more error)", "errors": { "email": [ "The email field must be a valid email address." ], "password": [ "The password field must be at least 8 characters." ] }}
Validation errors are automatically handled by Laravel’s FormRequest classes and return 422 status codes with detailed field-level errors.
POST /api/auth/loginAccept-Language: esContent-Type: application/json{"email": "[email protected]", "password": "wrong"}
{ "status": 400, "message": "No podemos encontrar un usuario con esa dirección de correo electrónico.", "errors": { "email": "No podemos encontrar un usuario con esa dirección de correo electrónico." }}
See Localization for more details on multi-language support.
Don’t return 200 OK for error conditions. Use the correct 4xx or 5xx status code.
// Goodreturn ApiResponse::error( status: Response::HTTP_NOT_FOUND, message: 'Resource not found');// Badreturn ApiResponse::success( message: 'Resource not found', data: []);
Provide specific error messages
Give users enough information to fix the issue without exposing sensitive details.
// Good'errors' => ['email' => 'User with this email does not exist']// Bad (too vague)'errors' => ['error' => 'Something went wrong']// Bad (too detailed/security risk)'errors' => ['db' => 'MySQL connection failed: host=192.168.1.1']
Use localized error messages
Always use translation keys instead of hardcoded strings.
// Goodmessage: __('messages.common.not_found', ['item' => 'Article'])// Badmessage: 'Article not found'
Include field-level errors for validation
Map validation errors to specific fields so clients can highlight problem areas.
'errors' => [ 'email' => ['Email is required', 'Email must be valid'], 'password' => ['Password must be at least 8 characters']]
Keep error responses consistent
Always return the same structure: {status, message, errors} for all errors.
// Success (200){ "status": 200, "message": "User logged in successfully.", "data": { "user": {...}, "token": "eyJ0eXAiOiJKV1QiLCJhbGc...", "expires_in": 3600 }}// Invalid credentials (401){ "status": 401, "message": "These credentials do not match our records.", "errors": { "password": "These credentials do not match our records." }}// User not found (400){ "status": 400, "message": "We can't find a user with that email address.", "errors": { "email": "We can't find a user with that email address." }}