unicon.matthews.common.advice.ExceptionHandlerControllerAdvice   A
last analyzed

Complexity

Total Complexity 23

Size/Duplication

Total Lines 147
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 147
rs 10
eloc 107
wmc 23

17 Methods

Rating   Name   Duplication   Size   Complexity  
A handleInvalidRestRequestException(HttpServletRequest,InvalidXAPIRequestException) 0 6 1
A handleNotImplementedException(HttpServletRequest,NotFoundException) 0 6 1
A test(NestedServletException) 0 4 1
A eventExceptionHandler(HttpServletRequest,Exception) 0 6 1
A log(Exception,MessageResponse) 0 3 1
A buildDate() 0 2 1
A genericExceptionHandler(HttpServletRequest,Exception) 0 6 1
A handleUnrecognizedPropertyException(HttpServletRequest,UnrecognizedPropertyException) 0 7 1
A oneRosterExceptionHandler(HttpServletRequest,Exception) 0 6 1
A handleNotImplementedException(HttpServletRequest,NotImplementedException) 0 6 1
A handleMethodArgumentNotValidException(HttpServletRequest,MethodArgumentNotValidException) 0 17 3
A handleHttpMessageNotReadableException(HttpServletRequest,HttpMessageNotReadableException) 0 15 3
A logError(MessageResponse) 0 2 1
A caliperExceptionHandler(HttpServletRequest,Exception) 0 6 1
A genericBadRequestHandler(HttpServletRequest,Exception) 0 6 1
A logException(Exception) 0 2 1
A runTimeExceptionHandler(HttpServletRequest,Exception) 0 8 3
1
package unicon.matthews.common.advice;
2
3
import com.fasterxml.jackson.core.JsonProcessingException;
4
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
5
import org.slf4j.Logger;
6
import org.slf4j.LoggerFactory;
7
import org.springframework.data.crossstore.ChangeSetPersister;
8
import org.springframework.http.converter.HttpMessageNotReadableException;
9
import org.springframework.validation.FieldError;
10
import org.springframework.validation.ObjectError;
11
import org.springframework.web.bind.MethodArgumentNotValidException;
12
import org.springframework.web.bind.annotation.ResponseStatus;
13
import org.springframework.web.bind.annotation.RestControllerAdvice;
14
15
import org.springframework.http.HttpStatus;
16
import org.springframework.web.bind.annotation.ExceptionHandler;
17
import org.springframework.web.util.NestedServletException;
18
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
0 ignored issues
show
Comprehensibility Best Practice introduced by
Use classes from the Java API instead of Sun classes.
Loading history...
19
import unicon.matthews.caliper.exception.CaliperNotFoundException;
20
import unicon.matthews.caliper.exception.EventNotFoundException;
21
import unicon.matthews.common.exception.BadRequestException;
22
import unicon.matthews.common.exception.MessageResponse;
23
import unicon.matthews.oneroster.exception.OneRosterNotFoundException;
24
import unicon.matthews.xapi.exception.InvalidXAPIRequestException;
25
26
import javax.servlet.http.HttpServletRequest;
27
import java.time.LocalDateTime;
28
import java.time.format.DateTimeFormatter;
29
import java.util.ArrayList;
30
import java.util.List;
31
32
/**
33
 * @author xchopin <[email protected]>
34
 * @author groybal <[email protected]>
35
 */
36
@RestControllerAdvice
37
public class ExceptionHandlerControllerAdvice {
38
39
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerControllerAdvice.class);
40
    private static final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
41
42
    private String buildDate() {
43
        return LocalDateTime.now().format(formatter);
44
    }
45
46
    private void logException(Exception e) {
47
        logger.debug("Exception message: {}", e.getMessage());
48
    }
49
50
    private void logError(MessageResponse error) {
51
        logger.error("Returning error: {}", error);
52
    }
53
54
    private void log(Exception e, MessageResponse error) {
55
        logException(e);
56
        logError(error);
57
    }
58
59
    @ExceptionHandler(Exception.class)
60
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
61
    public MessageResponse genericExceptionHandler(HttpServletRequest request, Exception e) {
62
        MessageResponse response = new MessageResponse(HttpStatus.INTERNAL_SERVER_ERROR, buildDate(), request, e.getLocalizedMessage());
63
        log(e, response);
64
        return response;
65
    }
66
67
    @ExceptionHandler(NotImplementedException.class)
68
    @ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
69
    public MessageResponse handleNotImplementedException(HttpServletRequest request, NotImplementedException e) {
70
        MessageResponse response = new MessageResponse(HttpStatus.NOT_IMPLEMENTED, buildDate(), request, e.getLocalizedMessage());
71
        log(e, response);
72
        return response;
73
    }
74
75
    @ExceptionHandler(ChangeSetPersister.NotFoundException.class)
76
    @ResponseStatus(HttpStatus.NOT_FOUND)
77
    public MessageResponse handleNotImplementedException(HttpServletRequest request, ChangeSetPersister.NotFoundException e) {
78
        MessageResponse response = new MessageResponse(HttpStatus.NOT_FOUND, buildDate(), request, e.getLocalizedMessage());
79
        log(e, response);
80
        return response;
81
    }
82
83
    @ExceptionHandler(InvalidXAPIRequestException.class)
84
    @ResponseStatus(HttpStatus.BAD_REQUEST)
85
    public MessageResponse handleInvalidRestRequestException(HttpServletRequest request, InvalidXAPIRequestException e) {
86
        MessageResponse response = new MessageResponse(HttpStatus.BAD_REQUEST, buildDate(), request, e.getLocalizedMessage());
87
        log(e, response);
88
        return response;
89
    }
90
91
    @ExceptionHandler(MethodArgumentNotValidException.class)
92
    @ResponseStatus(HttpStatus.BAD_REQUEST)
93
    public MessageResponse handleMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
94
        List<String> errorMessages = new ArrayList<>();
95
        for (ObjectError oe : e.getBindingResult().getAllErrors()) {
96
            if (oe instanceof FieldError) {
97
                final FieldError fe = (FieldError)oe;
98
                final String msg = String.format(
99
                        "Field error in object '%s' on field '%s': rejected value [%s].", fe.getObjectName(), fe.getField(), fe.getRejectedValue());
100
                errorMessages.add(msg);
101
            } else {
102
                errorMessages.add(oe.toString());
103
            }
104
        }
105
        MessageResponse response = new MessageResponse(HttpStatus.BAD_REQUEST, buildDate(), request, errorMessages);
106
        log(e, response);
107
        return response;
108
    }
109
110
    @ExceptionHandler(org.springframework.web.util.NestedServletException.class)
111
    public void test(NestedServletException e) {
112
        Throwable t = e.getCause();
113
        logger.debug("*************************** "+t.getClass().getName());
114
    }
115
116
    @ExceptionHandler(UnrecognizedPropertyException.class)
117
    @ResponseStatus(HttpStatus.BAD_REQUEST)
118
    public MessageResponse handleUnrecognizedPropertyException(final HttpServletRequest request, UnrecognizedPropertyException e) {
119
        String errorMessage = String.format("Unrecognized property: [%s].", e.getPropertyName());
120
        MessageResponse response = new MessageResponse(HttpStatus.BAD_REQUEST, buildDate(), request, errorMessage);
121
        log(e, response);
122
        return response;
123
    }
124
125
    @ExceptionHandler(HttpMessageNotReadableException.class)
126
    @ResponseStatus(HttpStatus.BAD_REQUEST)
127
    public MessageResponse handleHttpMessageNotReadableException(HttpServletRequest request, HttpMessageNotReadableException e) {
128
        if (e.getCause() instanceof UnrecognizedPropertyException) {
129
            return handleUnrecognizedPropertyException(request, (UnrecognizedPropertyException)e.getCause());
130
        } else {
131
            MessageResponse response;
132
            if (e.getCause() instanceof JsonProcessingException) {
133
                JsonProcessingException jpe = (JsonProcessingException)e.getCause();
134
                response = new MessageResponse(HttpStatus.BAD_REQUEST, buildDate(), request, jpe.getOriginalMessage());
135
            } else {
136
                response = new MessageResponse(HttpStatus.BAD_REQUEST, buildDate(), request, e.getMessage());
137
            }
138
            log(e, response);
139
            return response;
140
        }
141
    }
142
143
    @ExceptionHandler(RuntimeException.class)
144
    public MessageResponse runTimeExceptionHandler(HttpServletRequest request, Exception e) {
145
        if (e.getCause() instanceof OneRosterNotFoundException)
146
            return oneRosterExceptionHandler(request, e);
147
        else if (e.getCause() instanceof CaliperNotFoundException)
148
            return caliperExceptionHandler(request, e);
149
        else
150
            return genericExceptionHandler(request, e);
151
    }
152
153
    @ExceptionHandler(OneRosterNotFoundException.class)
154
    @ResponseStatus(HttpStatus.NOT_FOUND)
155
    public MessageResponse oneRosterExceptionHandler(HttpServletRequest request, Exception e) {
156
        MessageResponse response = new MessageResponse(HttpStatus.NOT_FOUND, buildDate(), request, e.getLocalizedMessage());
157
        log(e, response);
158
        return response;
159
    }
160
161
    @ExceptionHandler(CaliperNotFoundException.class)
162
    @ResponseStatus(HttpStatus.NOT_FOUND)
163
    public MessageResponse caliperExceptionHandler(HttpServletRequest request, Exception e) {
164
        MessageResponse response = new MessageResponse(HttpStatus.NOT_FOUND, buildDate(), request, e.getLocalizedMessage());
165
        log(e, response);
166
        return response;
167
    }
168
169
    @ExceptionHandler(EventNotFoundException.class)
170
    @ResponseStatus(HttpStatus.NOT_FOUND)
171
    public MessageResponse eventExceptionHandler(HttpServletRequest request, Exception e) {
172
        MessageResponse response = new MessageResponse(HttpStatus.NOT_FOUND, buildDate(), request, e.getLocalizedMessage());
173
        log(e, response);
174
        return response;
175
    }
176
177
    @ExceptionHandler(BadRequestException.class)
178
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
179
    public MessageResponse genericBadRequestHandler(HttpServletRequest request, Exception e) {
180
        MessageResponse response = new MessageResponse(HttpStatus.BAD_REQUEST, buildDate(), request, e.getLocalizedMessage());
181
        log(e, response);
182
        return response;
183
    }
184
185
}
186