1
+ package sample ;
2
+
3
+ import java .util .ArrayList ;
4
+ import java .util .List ;
5
+ import java .util .Set ;
6
+ import java .util .UUID ;
7
+
8
+ import javax .validation .ConstraintViolation ;
9
+ import javax .validation .ConstraintViolationException ;
10
+
11
+ import org .slf4j .Logger ;
12
+ import org .slf4j .LoggerFactory ;
13
+ import org .springframework .http .HttpStatus ;
14
+ import org .springframework .http .MediaType ;
15
+ import org .springframework .http .ResponseEntity ;
16
+ import org .springframework .http .converter .HttpMessageNotReadableException ;
17
+ import org .springframework .validation .FieldError ;
18
+ import org .springframework .validation .ObjectError ;
19
+ import org .springframework .web .HttpMediaTypeNotSupportedException ;
20
+ import org .springframework .web .bind .MethodArgumentNotValidException ;
21
+ import org .springframework .web .bind .MissingServletRequestParameterException ;
22
+ import org .springframework .web .bind .annotation .ControllerAdvice ;
23
+ import org .springframework .web .bind .annotation .ExceptionHandler ;
24
+ import org .springframework .web .bind .annotation .RequestMapping ;
25
+ import org .springframework .web .bind .annotation .ResponseStatus ;
26
+
27
+
28
+
29
+ @ ControllerAdvice ()
30
+ @ RequestMapping (produces = MediaType .APPLICATION_JSON_VALUE )
31
+ public class GlobalControllerAdvice //extends ResponseEntityExceptionHandler
32
+ {
33
+ /**
34
+ * Note use base class if you wish to leverage its handling.
35
+ * Some code will need changing.
36
+ */
37
+ private static final Logger logger = LoggerFactory .getLogger (GlobalControllerAdvice .class );
38
+
39
+ @ ExceptionHandler (Throwable .class )
40
+ @ ResponseStatus (code = HttpStatus .INTERNAL_SERVER_ERROR )
41
+ public ResponseEntity < Problem > problem (final Throwable e ) {
42
+ String message =e .getMessage ();
43
+ //might actually prefer to use a geeric mesasge
44
+
45
+ message ="Problem occured" ;
46
+ UUID uuid = UUID .randomUUID ();
47
+ String logRef =uuid .toString ();
48
+ logger .error ("logRef=" +logRef , message , e );
49
+ return new ResponseEntity <Problem > (new Problem (logRef , message ), HttpStatus .INTERNAL_SERVER_ERROR );
50
+ }
51
+
52
+
53
+
54
+ @ ExceptionHandler (MethodArgumentNotValidException .class )
55
+ @ ResponseStatus (code = HttpStatus .BAD_REQUEST )
56
+ public ResponseEntity <ErrorMessage > handleMethodArgumentNotValid (MethodArgumentNotValidException ex
57
+ ) {
58
+ List <FieldError > fieldErrors = ex .getBindingResult ().getFieldErrors ();
59
+ List <ObjectError > globalErrors = ex .getBindingResult ().getGlobalErrors ();
60
+ List <String > errors = new ArrayList <>(fieldErrors .size () + globalErrors .size ());
61
+ String error ;
62
+ for (FieldError fieldError : fieldErrors ) {
63
+ error = fieldError .getField () + ", " + fieldError .getDefaultMessage ();
64
+ errors .add (error );
65
+ }
66
+ for (ObjectError objectError : globalErrors ) {
67
+ error = objectError .getObjectName () + ", " + objectError .getDefaultMessage ();
68
+ errors .add (error );
69
+ }
70
+ ErrorMessage errorMessage = new ErrorMessage (errors );
71
+
72
+ //Object result=ex.getBindingResult();//instead of above can allso pass the more detailed bindingResult
73
+ return new ResponseEntity (errorMessage , HttpStatus .BAD_REQUEST );
74
+ }
75
+ @ ExceptionHandler (ConstraintViolationException .class )
76
+ @ ResponseStatus (code = HttpStatus .BAD_REQUEST )
77
+ public ResponseEntity <ErrorMessage > handleConstraintViolatedException (ConstraintViolationException ex
78
+ ) {
79
+ Set <ConstraintViolation <?>> constraintViolations = ex .getConstraintViolations ();
80
+
81
+
82
+ List <String > errors = new ArrayList <>(constraintViolations .size () );
83
+ String error ;
84
+ for (ConstraintViolation constraintViolation : constraintViolations ) {
85
+
86
+ error = constraintViolation .getMessage ();
87
+ errors .add (error );
88
+ }
89
+
90
+ ErrorMessage errorMessage = new ErrorMessage (errors );
91
+ return new ResponseEntity (errorMessage , HttpStatus .BAD_REQUEST );
92
+ }
93
+
94
+ @ ExceptionHandler (MissingServletRequestParameterException .class )
95
+ @ ResponseStatus (code = HttpStatus .BAD_REQUEST )
96
+ public ResponseEntity <ErrorMessage > handleMissingServletRequestParameterException (MissingServletRequestParameterException ex
97
+ ) {
98
+
99
+ List <String > errors = new ArrayList <>( );
100
+ String error =ex .getParameterName ()+", " +ex .getMessage ();
101
+ errors .add (error );
102
+ ErrorMessage errorMessage = new ErrorMessage (errors );
103
+ return new ResponseEntity (errorMessage , HttpStatus .BAD_REQUEST );
104
+ }
105
+
106
+
107
+ @ ExceptionHandler (HttpMediaTypeNotSupportedException .class )
108
+ @ ResponseStatus (code = HttpStatus .UNSUPPORTED_MEDIA_TYPE )
109
+ public ResponseEntity <ErrorMessage > handleHttpMediaTypeNotSupported (HttpMediaTypeNotSupportedException ex
110
+ ) {
111
+ String unsupported = "Unsupported content type: " + ex .getContentType ();
112
+ String supported = "Supported content types: " + MediaType .toString (ex .getSupportedMediaTypes ());
113
+ ErrorMessage errorMessage = new ErrorMessage (unsupported , supported );
114
+ return new ResponseEntity (errorMessage , HttpStatus .UNSUPPORTED_MEDIA_TYPE );
115
+ }
116
+
117
+ @ ExceptionHandler (HttpMessageNotReadableException .class )
118
+ @ ResponseStatus (code = HttpStatus .BAD_REQUEST )
119
+ public ResponseEntity <ErrorMessage > handleHttpMessageNotReadable (HttpMessageNotReadableException ex ) {
120
+ Throwable mostSpecificCause = ex .getMostSpecificCause ();
121
+ ErrorMessage errorMessage ;
122
+ if (mostSpecificCause != null ) {
123
+ String exceptionName = mostSpecificCause .getClass ().getName ();
124
+ String message = mostSpecificCause .getMessage ();
125
+ errorMessage = new ErrorMessage (exceptionName , message );
126
+ } else {
127
+ errorMessage = new ErrorMessage (ex .getMessage ());
128
+ }
129
+ return new ResponseEntity (errorMessage , HttpStatus .BAD_REQUEST );
130
+ }
131
+
132
+ }
0 commit comments