Skip to content

Commit 5d9eada

Browse files
committed
add additional global exception handler scenarios
1 parent 86ce89d commit 5d9eada

1 file changed

Lines changed: 31 additions & 5 deletions

File tree

src/main/java/com/taskmanagerapi/exception/GlobalExceptionHandler.java

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import org.springframework.http.ResponseEntity;
55
import org.springframework.web.bind.annotation.ExceptionHandler;
66
import org.springframework.web.bind.annotation.RestControllerAdvice;
7+
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
78

89
import java.time.LocalDateTime;
910
import java.time.temporal.ChronoUnit;
@@ -12,12 +13,37 @@
1213
@RestControllerAdvice
1314
public class GlobalExceptionHandler {
1415

16+
private final LocalDateTime time = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);
17+
1518
@ExceptionHandler(TaskNotFoundException.class)
1619
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+
));
2248
}
2349
}

0 commit comments

Comments
 (0)