Skip to main content

Overview

The Kin Conecta API uses standard HTTP status codes and returns detailed error responses in JSON format. All errors follow a consistent structure to make debugging and error handling straightforward.

Error Response Format

When an error occurs, the API returns a JSON object with the following structure:
{
  "status": 404,
  "error": "Not Found",
  "message": "User with id 999 not found",
  "timestamp": "2026-03-11T10:30:00"
}

Error Response Fields

FieldTypeDescription
statusIntegerHTTP status code
errorStringHTTP status reason phrase
messageStringDetailed error message describing what went wrong
timestampDateTimeWhen the error occurred (ISO 8601 format)

HTTP Status Codes

The API uses standard HTTP status codes to indicate the success or failure of requests.

Success Codes

CodeStatusDescription
200OKRequest succeeded (GET, PUT)
201CreatedResource created successfully (POST)
204No ContentResource deleted successfully (DELETE)

Client Error Codes

CodeStatusDescriptionCommon Causes
400Bad RequestInvalid request format or dataMissing required fields, invalid JSON, malformed data
401UnauthorizedAuthentication required or failedMissing/invalid token, expired session
403ForbiddenInsufficient permissionsUser doesn’t have access to resource
404Not FoundResource doesn’t existInvalid ID, resource was deleted
409ConflictResource conflictDuplicate unique values, constraint violation
422Unprocessable EntityValidation failedInvalid data format, business logic violation

Server Error Codes

CodeStatusDescriptionCommon Causes
500Internal Server ErrorUnexpected server errorDatabase connection issues, unhandled exceptions
503Service UnavailableService temporarily unavailableDatabase down, maintenance mode

Common Error Scenarios

Resource Not Found (404)

Occurs when trying to access a resource that doesn’t exist.

Example Request

curl -X GET "http://localhost:8080/api/users/999"

Error Response

{
  "status": 404,
  "error": "Not Found",
  "message": "User with id 999 not found",
  "timestamp": "2026-03-11T10:30:00"
}
The ResourceNotFoundException is thrown by the service layer when a requested entity cannot be found in the database.

Bad Request (400)

Occurs when the request contains invalid data or is malformed.

Example Request

curl -X POST "http://localhost:8080/api/users" \
  -H "Content-Type: application/json" \
  -d '{
    "role": "INVALID_ROLE",
    "email": "not-an-email"
  }'

Error Response

{
  "status": 400,
  "error": "Bad Request",
  "message": "Invalid role value: INVALID_ROLE",
  "timestamp": "2026-03-11T10:30:00"
}
The BadRequestException is used for validation errors and invalid input data. Always validate data on the client side before sending requests.

Internal Server Error (500)

Occurs when an unexpected error happens on the server.

Example Response

{
  "status": 500,
  "error": "Internal Server Error",
  "message": "Unexpected internal server error",
  "timestamp": "2026-03-11T10:30:00"
}
For security reasons, internal server errors return a generic message. Check server logs for detailed error information.

Error Handling by Endpoint

Create Operations (POST)

curl -X POST "http://localhost:8080/api/languages" \
  -H "Content-Type: application/json" \
  -d '{
    "languageCode": "es",
    "name": "Espanol"
  }'

# Response: 201 Created
{
  "languageCode": "es",
  "name": "Espanol",
  "createdAt": "2026-03-11T10:30:00"
}

Read Operations (GET)

curl -X GET "http://localhost:8080/api/faq_items/1"

# Response: 200 OK
{
  "faqItemId": 1,
  "faqCategoryId": 1,
  "question": "Como pago un tour?",
  "answer": "Puedes pagar con tarjeta.",
  "isActive": true
}

Update Operations (PUT)

curl -X PUT "http://localhost:8080/api/faq_items/1" \
  -H "Content-Type: application/json" \
  -d '{
    "faqCategoryId": 1,
    "question": "Como pago un tour?",
    "answer": "Tarjeta, transferencia o efectivo.",
    "isActive": true,
    "sortOrder": 1
  }'

# Response: 200 OK
{
  "faqItemId": 1,
  "faqCategoryId": 1,
  "question": "Como pago un tour?",
  "answer": "Tarjeta, transferencia o efectivo.",
  "isActive": true
}

Delete Operations (DELETE)

curl -X DELETE "http://localhost:8080/api/faq_items/1"

# Response: 204 No Content
# (No response body)

Handling Composite Keys

Some endpoints use composite keys (multiple path parameters). Errors can occur if any part of the key is invalid.

Example with Composite Key

curl -X GET "http://localhost:8080/api/tourist_profile_languages/1/es"

# Success: 200 OK
{
  "userId": 1,
  "languageCode": "es",
  "proficiencyLevel": "NATIVE"
}

# Error: 404 Not Found
curl -X GET "http://localhost:8080/api/tourist_profile_languages/999/xx"

{
  "status": 404,
  "error": "Not Found",
  "message": "Tourist profile language not found for userId 999 and languageCode xx",
  "timestamp": "2026-03-11T10:30:00"
}

Client-Side Error Handling

Implement robust error handling in your client application:
async function createUser(userData) {
  try {
    const response = await fetch('http://localhost:8080/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(userData)
    });

    if (!response.ok) {
      const error = await response.json();
      
      switch (error.status) {
        case 400:
          console.error('Invalid data:', error.message);
          break;
        case 404:
          console.error('Resource not found:', error.message);
          break;
        case 500:
          console.error('Server error:', error.message);
          break;
        default:
          console.error('Unexpected error:', error.message);
      }
      
      throw new Error(error.message);
    }

    return await response.json();
  } catch (error) {
    console.error('Request failed:', error);
    throw error;
  }
}

Troubleshooting Common Issues

Error: 500 Internal Server Error with message about database connectivityCommon Causes:
  • MySQL server is not running
  • Incorrect database credentials in application.properties
  • Database schema doesn’t exist
  • Network/firewall blocking database port (3306)
Solutions:
  1. Verify MySQL server is running: mysql -u root -p
  2. Check database configuration in src/main/resources/application.properties
  3. Ensure schema exists: Run kinConnect.sql script
  4. Verify username/password match MySQL configuration
Error: Unknown database or Table doesn't existSolution:
  1. Check that schema name in spring.datasource.url matches actual schema
  2. Default schema is kin_conecta - verify in MySQL Workbench
  3. If using different name, either:
    • Update URL: jdbc:mysql://localhost:3306/kin_conecta
    • Or recreate schema with matching name
Error: Port 8080 already in useSolutions:
  1. Stop the process using port 8080
  2. Or configure different port in application.properties:
    server.port=8081
    
Error: 400 Bad Request with JSON parsing errorCommon Causes:
  • Missing quotes around strings
  • Trailing commas in JSON objects
  • Invalid escape sequences
  • Missing Content-Type header
Solution:
  1. Validate JSON with a linter
  2. Always include: Content-Type: application/json
  3. Use proper JSON encoding in your client library
Error: 400 Bad Request with message about invalid date formatSolution: Use ISO 8601 format:
  • Date: "2026-03-11" (YYYY-MM-DD)
  • DateTime: "2026-03-11T10:30:00" (YYYY-MM-DDTHH:mm:ss)
  • Include leading zeros for single-digit values
Error: 400 Bad Request with message about invalid enum valueSolution:
  • Enum values are CASE-SENSITIVE and must be UPPERCASE
  • Example: Use "TOURIST" not "tourist" or "Tourist"
  • Check API documentation for valid enum values

Error Response Implementation

The API uses a centralized exception handler to ensure consistent error responses across all endpoints.

Exception Handler

The GlobalExceptionHandler (located at src/main/java/org/generation/socialNetwork/configuration/exception/GlobalExceptionHandler.java) catches exceptions and converts them to standardized error responses:
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    // Handles ResourceNotFoundException -> 404 Not Found
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
        return build(HttpStatus.NOT_FOUND, ex.getMessage());
    }
    
    // Handles BadRequestException -> 400 Bad Request
    @ExceptionHandler(BadRequestException.class)
    public ResponseEntity<ErrorResponse> handleBadRequest(BadRequestException ex) {
        return build(HttpStatus.BAD_REQUEST, ex.getMessage());
    }
    
    // Handles all other exceptions -> 500 Internal Server Error
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGeneral(Exception ex) {
        return build(HttpStatus.INTERNAL_SERVER_ERROR, 
                    "Unexpected internal server error");
    }
}

Custom Exceptions

The API defines custom exception classes:
  • ResourceNotFoundException: Thrown when a requested resource doesn’t exist
  • BadRequestException: Thrown for invalid input or validation errors

Best Practices

Validate Before Sending

Validate data on the client side before making API requests to catch errors early.

Handle All Status Codes

Implement handlers for all possible status codes (200, 201, 204, 400, 404, 500).

Log Error Details

Log full error responses for debugging, but show user-friendly messages to users.

Implement Retry Logic

For 500 errors, implement exponential backoff retry logic with reasonable limits.

Next Steps

API Overview

Learn about API architecture and conventions

Authentication

Secure your API requests with authentication

Build docs developers (and LLMs) love