HTTP Topic
HTTP Status Codes and Error Handling
What You'll Learn:
-
Understanding status code categories (1xx-5xx)
-
Proper usage of common status codes
-
Designing effective error responses
Detailed Explanation:
Status Code Categories
1xx - Informational
-
Request received, continuing process
-
100 Continue: Client should continue with request body
-
101 Switching Protocols: Server agrees to switch protocols
2xx - Success
-
Request successfully received, understood, and accepted
-
200 OK: Standard success response
-
201 Created: Resource created successfully
-
204 No Content: Success but no content to return
3xx - Redirection
-
Further action needed to complete request
-
301 Moved Permanently: Resource has new permanent URL
-
302 Found: Temporary redirection
-
304 Not Modified: Cached version is still valid
4xx - Client Error
-
Client appears to have erred
-
400 Bad Request: Malformed request syntax
-
401 Unauthorized: Authentication required
-
403 Forbidden: Authenticated but not authorized
-
404 Not Found: Resource doesn't exist
-
409 Conflict: Request conflicts with current state
5xx - Server Error
-
Server failed to fulfill valid request
-
500 Internal Server Error: Generic server error
-
502 Bad Gateway: Invalid response from upstream
-
503 Service Unavailable: Server temporarily unavailable
Common Status Code Usage
Success Responses:
# 200 OK - Standard success
HTTP/1.1 200 OK
Content-Type: application/json
{"id": 123, "name": "John Doe"}
# 201 Created - Resource created
HTTP/1.1 201 Created
Location: /api/users/123
Content-Type: application/json
{"id": 123, "name": "John Doe"}
# 204 No Content - Success, no body
HTTP/1.1 204 No Content
Client Error Responses:
# 400 Bad Request - Validation error
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "VALIDATION_ERROR",
"message": "Email format is invalid",
"details": [
{"field": "email", "message": "must be a valid email address"}
]
}
# 401 Unauthorized - Authentication required
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"
Content-Type: application/json
{
"error": "UNAUTHORIZED",
"message": "Authentication required"
}
# 404 Not Found - Resource doesn't exist
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": "NOT_FOUND",
"message": "User with id 999 not found"
}
Error Response Design Best Practices
Standard Error Response Format:
{
"error": "ERROR_CODE",
"message": "Human readable message",
"details": [
{"field": "email", "message": "must be valid email"}
],
"timestamp": "2023-01-23T10:30:45Z",
"path": "/api/users",
"requestId": "req-123456"
}
Spring Boot Error Handling Implementation:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {
ErrorResponse error = ErrorResponse.builder()
.error("USER_NOT_FOUND")
.message(ex.getMessage())
.timestamp(Instant.now())
.path(getCurrentRequestPath())
.build();
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationErrors(MethodArgumentNotValidException ex) {
List<FieldError> fieldErrors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> new FieldError(error.getField(), error.getDefaultMessage()))
.collect(Collectors.toList());
ErrorResponse error = ErrorResponse.builder()
.error("VALIDATION_ERROR")
.message("Request validation failed")
.details(fieldErrors)
.timestamp(Instant.now())
.build();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
ErrorResponse error = ErrorResponse.builder()
.error("INTERNAL_ERROR")
.message("An unexpected error occurred")
.timestamp(Instant.now())
.build();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
Status Code Selection Guide
| Scenario | Recommended Status Code |
|---|---|
| Successful resource retrieval | 200 OK |
| Resource created | 201 Created |
| Resource updated | 200 OK or 204 No Content |
| Resource deleted | 204 No Content |
| Invalid request body | 400 Bad Request |
| Authentication required | 401 Unauthorized |
| Insufficient permissions | 403 Forbidden |
| Resource not found | 404 Not Found |
| Conflict (e.g., duplicate) | 409 Conflict |
| Server error | 500 Internal Server Error |
Comments (0)
No comments yet. Be the first to comment!