1
1
package com .learning .exception ;
2
2
3
+ import com .learning .payload .response .ErrorResponse ;
4
+ import org .springframework .boot .web .servlet .error .DefaultErrorAttributes ;
5
+ import org .springframework .boot .web .servlet .error .ErrorAttributes ;
6
+ import org .springframework .context .annotation .Bean ;
3
7
import org .springframework .http .HttpStatus ;
4
8
import org .springframework .http .ResponseEntity ;
5
- import org .springframework .web . bind . annotation . ControllerAdvice ;
9
+ import org .springframework .security . access . AccessDeniedException ;
6
10
import org .springframework .web .bind .annotation .ExceptionHandler ;
11
+ import org .springframework .web .bind .annotation .RestControllerAdvice ;
7
12
import org .springframework .web .context .request .WebRequest ;
8
13
9
- @ ControllerAdvice
14
+ import javax .servlet .http .HttpServletResponse ;
15
+ import java .io .IOException ;
16
+ import java .util .Map ;
17
+
18
+ @ RestControllerAdvice
10
19
public class GlobalExceptionHandler {
11
20
21
+ @ Bean
22
+ public ErrorAttributes errorAttributes () {
23
+ return new DefaultErrorAttributes () {
24
+ public Map <String , Object > getErrorAttributes (WebRequest webRequest , boolean includeStackTrace ) {
25
+ Map <String , Object > errorAttributes = super .getErrorAttributes (webRequest , includeStackTrace );
26
+ errorAttributes .remove ("exception" );
27
+ return errorAttributes ;
28
+ }
29
+ };
30
+ }
31
+
12
32
/**
13
33
* Resource not found exception response entity.
14
34
*
@@ -31,10 +51,26 @@ public ResponseEntity<?> resourceNotFoundException(
31
51
* @param request the request
32
52
* @return the response entity
33
53
*/
34
- @ ExceptionHandler (Exception .class )
54
+ /* @ExceptionHandler(Exception.class)
35
55
public ResponseEntity<?> globleExcpetionHandler(Exception ex, WebRequest request) {
36
56
ErrorResponse errorDetails =
37
57
new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.toString() ,ex.getMessage(), request.getDescription(false));
38
58
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
59
+ }*/
60
+
61
+ @ ExceptionHandler (CustomException .class )
62
+ public void handleCustomException (HttpServletResponse res , CustomException ex ) throws IOException {
63
+ res .sendError (ex .getHttpStatus ().value (), ex .getMessage ());
39
64
}
65
+
66
+ @ ExceptionHandler (AccessDeniedException .class )
67
+ public void handleAccessDeniedException (HttpServletResponse res ) throws IOException {
68
+ res .sendError (HttpStatus .FORBIDDEN .value (), "Access denied" );
69
+ }
70
+
71
+ @ ExceptionHandler (Exception .class )
72
+ public void handleException (HttpServletResponse res ) throws IOException {
73
+ res .sendError (HttpStatus .BAD_REQUEST .value (), "Something went wrong" );
74
+ }
75
+
40
76
}
0 commit comments