|
4 | 4 | import org.springframework.http.ResponseEntity; |
5 | 5 | import org.springframework.web.bind.annotation.ExceptionHandler; |
6 | 6 | import org.springframework.web.bind.annotation.RestControllerAdvice; |
| 7 | +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; |
7 | 8 |
|
8 | 9 | import java.time.LocalDateTime; |
9 | 10 | import java.time.temporal.ChronoUnit; |
|
12 | 13 | @RestControllerAdvice |
13 | 14 | public class GlobalExceptionHandler { |
14 | 15 |
|
| 16 | + private final LocalDateTime time = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS); |
| 17 | + |
15 | 18 | @ExceptionHandler(TaskNotFoundException.class) |
16 | 19 | public ResponseEntity<Map<String, Object>> handleTaskNotFound(TaskNotFoundException ex) { |
17 | | - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of( |
18 | | - "error", ex.getMessage(), |
19 | | - "status", 404, |
20 | | - "timestamp", LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS) |
21 | | - )); |
| 20 | + return ResponseEntity.status(HttpStatus.NOT_FOUND).body( |
| 21 | + Map.of( |
| 22 | + "error", ex.getMessage(), |
| 23 | + "status", 404, |
| 24 | + "timestamp", time |
| 25 | + ) |
| 26 | + ); |
| 27 | + } |
| 28 | + |
| 29 | + @ExceptionHandler(Exception.class) |
| 30 | + public ResponseEntity<Map<String, Object>> handleGenericError() { |
| 31 | + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body( |
| 32 | + Map.of( |
| 33 | + "error", "An unexpected error occurred", |
| 34 | + "status", 500, |
| 35 | + "timestamp", time |
| 36 | + ) |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + @ExceptionHandler(MethodArgumentTypeMismatchException.class) |
| 41 | + public ResponseEntity<Map<String, Object>> handleTypeMismatch(MethodArgumentTypeMismatchException ex) { |
| 42 | + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body( |
| 43 | + Map.of( |
| 44 | + "error", "Invalid status value: " + ex.getValue(), |
| 45 | + "status", 400, |
| 46 | + "timestamp", time |
| 47 | + )); |
22 | 48 | } |
23 | 49 | } |
0 commit comments