Add API error handling
Problem Context
We need consistent error handling across our REST API endpoints with proper logging and response formatting.
Intermediate
100 points
File Changes (1)
src/main/java/com/example/controller/ProductController.java
MODIFIED
@@ -15 +15 @@
| 15 | 15 | private static final Logger log = LoggerFactory.getLogger(ProductController.class); |
| 16 | + |
|
| 17 | + @GetMapping("/{id}") |
|
| 18 | + public ResponseEntity<?> getProduct(@PathVariable Long id) { |
|
| 19 | + try { |
|
| 20 | + Product product = productService.findById(id); |
|
| 21 | + return ResponseEntity.ok(product); |
|
| 22 | + } catch (ProductNotFoundException e) { |
|
| 23 | + log.error("Product not found: {}", id, e); |
|
| 24 | + Map<String, Object> error = new HashMap<>(); |
|
| 25 | + error.put("error", "Product not found"); |
|
| 26 | + error.put("code", "PRODUCT_NOT_FOUND"); |
|
| 27 | + error.put("timestamp", Instant.now()); |
|
| 28 | + return ResponseEntity.status(404).body(error); |
|
| 29 | + } catch (Exception e) { |
|
| 30 | + log.error("Unexpected error getting product: {}", id, e); |
|
| 31 | + Map<String, Object> error = new HashMap<>(); |
|
| 32 | + error.put("error", "Internal server error"); |
|
| 33 | + error.put("code", "INTERNAL_ERROR"); |
|
| 34 | + error.put("timestamp", Instant.now()); |
|
| 35 | + return ResponseEntity.status(500).body(error); |
|
| 36 | + } |
|
| 37 | + } |
|
| 38 | + |
|
| 39 | + @PostMapping |
|
| 40 | + public ResponseEntity<?> createProduct(@RequestBody ProductRequest request) { |
|
| 41 | + try { |
|
| 42 | + Product product = productService.create(request); |
|
| 43 | + return ResponseEntity.status(201).body(product); |
|
| 44 | + } catch (ValidationException e) { |
|
| 45 | + log.error("Validation error creating product", e); |
|
| 46 | + Map<String, Object> error = new HashMap<>(); |
|
| 47 | + error.put("error", e.getMessage()); |
|
| 48 | + error.put("code", "VALIDATION_ERROR"); |
|
| 49 | + error.put("timestamp", Instant.now()); |
|
| 50 | + return ResponseEntity.status(400).body(error); |
|
| 51 | + } catch (Exception e) { |
|
| 52 | + log.error("Unexpected error creating product", e); |
|
| 53 | + Map<String, Object> error = new HashMap<>(); |
|
| 54 | + error.put("error", "Internal server error"); |
|
| 55 | + error.put("code", "INTERNAL_ERROR"); |
|
| 56 | + error.put("timestamp", Instant.now()); |
|
| 57 | + return ResponseEntity.status(500).body(error); |
|
| 58 | + } |
|
| 59 | + } |
|
| 16 | 60 | } |
Login Required: You must be registered to submit reviews and receive AI feedback.
Register or
login to start reviewing!
Your Review
Review Tips
- Look for security vulnerabilities (SQL injection, XSS, etc.)
- Check for null pointer exceptions and error handling
- Consider performance implications
- Evaluate code maintainability and readability
- Check for proper resource management
- Look for logic errors or edge cases