1+ package taskmanagementsystem .exception ;
2+
3+ import org .springframework .http .HttpStatus ;
4+ import org .springframework .http .ResponseEntity ;
5+ import org .springframework .web .bind .MethodArgumentNotValidException ;
6+ import org .springframework .web .bind .annotation .ControllerAdvice ;
7+ import org .springframework .web .bind .annotation .ExceptionHandler ;
8+ import org .springframework .web .context .request .WebRequest ;
9+
10+ import java .time .LocalDateTime ;
11+ import java .util .Objects ;
12+
13+ @ ControllerAdvice
14+ public class GlobalExceptionHandler {
15+ @ ExceptionHandler (ResourceNotFoundException .class )
16+ public ResponseEntity <ErrorDetails > handleResourceNotFoundException (ResourceNotFoundException resourceNotFoundException ,
17+ WebRequest request ){
18+ var errorDetails = new ErrorDetails (
19+ LocalDateTime .now (),
20+ resourceNotFoundException .getMessage (),
21+ request .getDescription (false )
22+ );
23+ return new ResponseEntity <>(errorDetails , HttpStatus .BAD_REQUEST );
24+ }
25+
26+ @ ExceptionHandler (ApiException .class )
27+ public ResponseEntity <ErrorDetails > handleTaskApiException (ApiException exception ,
28+ WebRequest request ){
29+ var errorDetails = new ErrorDetails (
30+ LocalDateTime .now (),
31+ exception .getMessage (),
32+ request .getDescription (false )
33+ );
34+ return new ResponseEntity <>(errorDetails , HttpStatus .BAD_REQUEST );
35+ }
36+
37+ @ ExceptionHandler (MethodArgumentNotValidException .class )
38+ public ResponseEntity <ErrorDetails > handleMethodArgumentNotValidException (MethodArgumentNotValidException exception ,
39+ WebRequest request ){
40+ ErrorDetails errorDetails = new ErrorDetails (
41+ LocalDateTime .now (),
42+ Objects .requireNonNull (exception .getFieldError ()).getDefaultMessage (),
43+ request .getDescription (false )
44+ );
45+
46+ return new ResponseEntity <>(errorDetails , HttpStatus .BAD_REQUEST );
47+ }
48+ }
0 commit comments