2
2
3
3
import jakarta .servlet .http .HttpServletRequest ;
4
4
import org .springframework .http .HttpStatus ;
5
+ import org .springframework .security .access .AccessDeniedException ;
6
+ import org .springframework .security .core .AuthenticationException ;
7
+ import org .springframework .validation .FieldError ;
8
+ import org .springframework .web .bind .MethodArgumentNotValidException ;
5
9
import org .springframework .web .bind .annotation .ExceptionHandler ;
6
10
import org .springframework .web .bind .annotation .ResponseStatus ;
7
11
import org .springframework .web .bind .annotation .RestControllerAdvice ;
8
12
9
13
import java .time .LocalDateTime ;
14
+ import java .util .HashMap ;
15
+ import java .util .Map ;
10
16
11
17
@ RestControllerAdvice
12
18
public class GlobalExceptionHandler {
@@ -22,6 +28,44 @@ public ErrorMessage taskManagementExceptionHandler(TaskManagementException ex, H
22
28
.build ();
23
29
}
24
30
31
+ @ ExceptionHandler (AuthenticationException .class )
32
+ @ ResponseStatus (HttpStatus .UNAUTHORIZED )
33
+ public ErrorMessage authenticationExceptionHandler (AuthenticationException ex , HttpServletRequest request ) {
34
+
35
+ return ErrorMessage .builder ()
36
+ .path (request .getRequestURI ())
37
+ .message (ex .getMessage ())
38
+ .timestamp (LocalDateTime .now ().toString ())
39
+ .build ();
40
+ }
41
+
42
+ @ ExceptionHandler (AccessDeniedException .class )
43
+ @ ResponseStatus (HttpStatus .FORBIDDEN )
44
+ public ErrorMessage accessDeniedHandler (AccessDeniedException ex , HttpServletRequest request ) {
45
+
46
+ return ErrorMessage .builder ()
47
+ .path (request .getRequestURI ())
48
+ .message ("You do not have permission to access this resource." )
49
+ .timestamp (LocalDateTime .now ().toString ())
50
+ .build ();
51
+ }
52
+
53
+ @ ExceptionHandler (MethodArgumentNotValidException .class )
54
+ public ErrorMessage handleArgumentNotValidException (MethodArgumentNotValidException ex , HttpServletRequest request ) {
55
+
56
+ Map <String , String > errors = new HashMap <>();
57
+
58
+ for (FieldError error : ex .getBindingResult ().getFieldErrors ()) {
59
+ errors .put (error .getField (), error .getDefaultMessage ());
60
+ }
61
+
62
+ return ErrorMessage .builder ()
63
+ .path (request .getRequestURI ())
64
+ .message (errors )
65
+ .timestamp (LocalDateTime .now ().toString ())
66
+ .build ();
67
+ }
68
+
25
69
@ ExceptionHandler (Exception .class )
26
70
@ ResponseStatus (HttpStatus .NOT_FOUND )
27
71
public ErrorMessage exceptionHandler (Exception ex , HttpServletRequest request ) {
0 commit comments