11package com .example .SorokinSpringBoot .exceptions ;
22
3+ import com .example .SorokinSpringBoot .ErrorResponseDTO ;
4+ import jakarta .persistence .EntityNotFoundException ;
5+ import org .springframework .http .HttpStatus ;
36import org .springframework .http .ResponseEntity ;
47import org .springframework .web .bind .annotation .ControllerAdvice ;
58import org .springframework .web .bind .annotation .ExceptionHandler ;
69
10+ import java .time .LocalDateTime ;
711import java .util .logging .Logger ;
812
913@ ControllerAdvice
@@ -12,9 +16,42 @@ public class GlobalExceptionHandler {
1216 private static final Logger logger = Logger .getLogger (GlobalExceptionHandler .class .getName ());
1317
1418 @ ExceptionHandler (Exception .class )
15- public ResponseEntity <Void > handleGenericException (Exception exception ) {
16- logger .warning ("Handle exception" + exception );
17- return ResponseEntity .status (500 ).build ();
19+ public ResponseEntity <ErrorResponseDTO > handleGenericException (Exception exception ) {
20+ logger .warning ("Handle exception " + exception );
21+
22+ var errorDTO = new ErrorResponseDTO (
23+ "Internal server error" ,
24+ exception .getMessage (),
25+ LocalDateTime .now ()
26+ );
27+
28+ return ResponseEntity .status (HttpStatus .INTERNAL_SERVER_ERROR ).body (errorDTO );
29+ }
30+
31+ @ ExceptionHandler (EntityNotFoundException .class )
32+ public ResponseEntity <ErrorResponseDTO > handleEntityNotFound (Exception exception ) {
33+ logger .warning ("Handle EntityNotFound " + exception .getMessage ());
34+
35+ var errorDTO = new ErrorResponseDTO (
36+ "Entity not found error" ,
37+ exception .getMessage (),
38+ LocalDateTime .now ()
39+ );
40+
41+ return ResponseEntity .status (HttpStatus .NOT_FOUND ).body (errorDTO );
42+ }
43+
44+ @ ExceptionHandler (exception = {IllegalArgumentException .class , IllegalStateException .class })
45+ public ResponseEntity <ErrorResponseDTO > handleIllegalArgumentException (Exception exception ) {
46+ logger .warning ("Handle exception " + exception );
47+
48+ var errorDTO = new ErrorResponseDTO (
49+ "Entity not found error" ,
50+ exception .getMessage (),
51+ LocalDateTime .now ()
52+ );
53+
54+ return ResponseEntity .status (HttpStatus .BAD_REQUEST ).body (errorDTO );
1855 }
1956
2057}
0 commit comments