-
-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathExceptionHandlers.kt
More file actions
323 lines (296 loc) · 12.1 KB
/
Copy pathExceptionHandlers.kt
File metadata and controls
323 lines (296 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package io.tolgee
import io.sentry.Sentry
import io.swagger.v3.oas.annotations.media.Content
import io.swagger.v3.oas.annotations.media.Schema
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.tolgee.constants.Message
import io.tolgee.dtos.request.validators.ValidationErrorType
import io.tolgee.dtos.request.validators.exceptions.ValidationException
import io.tolgee.exceptions.BadRequestException
import io.tolgee.exceptions.ErrorException
import io.tolgee.exceptions.ErrorResponseBody
import io.tolgee.exceptions.ErrorResponseTyped
import io.tolgee.exceptions.NotFoundException
import io.tolgee.security.ratelimit.RateLimitBlockedException
import io.tolgee.security.ratelimit.RateLimitResponseBody
import io.tolgee.security.ratelimit.RateLimitedException
import io.tolgee.util.Logging
import io.tolgee.util.logger
import jakarta.persistence.EntityNotFoundException
import jakarta.servlet.http.HttpServletRequest
import org.apache.catalina.connector.ClientAbortException
import org.apache.commons.lang3.exception.ExceptionUtils
import org.hibernate.QueryException
import org.springframework.dao.InvalidDataAccessApiUsageException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.transaction.TransactionSystemException
import org.springframework.validation.BindException
import org.springframework.validation.FieldError
import org.springframework.validation.ObjectError
import org.springframework.web.HttpMediaTypeNotSupportedException
import org.springframework.web.HttpRequestMethodNotSupportedException
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.MissingServletRequestParameterException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
import org.springframework.web.multipart.MaxUploadSizeExceededException
import org.springframework.web.multipart.support.MissingServletRequestPartException
import org.springframework.web.servlet.resource.NoResourceFoundException
import java.io.IOException
import java.io.Serializable
import java.util.Arrays
import java.util.Collections
import java.util.function.Consumer
@RestControllerAdvice
class ExceptionHandlers : Logging {
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleValidationExceptions(
ex: MethodArgumentNotValidException,
): ResponseEntity<Map<String, Map<String, String>>> {
val errors: MutableMap<String, String> = HashMap()
ex.bindingResult.allErrors.forEach(
Consumer { error: ObjectError ->
val fieldName = (error as FieldError).field
val errorMessage = error.defaultMessage
errors[fieldName] = errorMessage ?: ""
},
)
return ResponseEntity(
Collections.singletonMap<String, Map<String, String>>(ValidationErrorType.STANDARD_VALIDATION.name, errors),
HttpStatus.BAD_REQUEST,
)
}
@ExceptionHandler(MethodArgumentTypeMismatchException::class)
fun handleValidationExceptions(ex: MethodArgumentTypeMismatchException): ResponseEntity<ErrorResponseBody> {
return ResponseEntity(
ErrorResponseBody(Message.WRONG_PARAM_TYPE.code, listOfNotNull(ex.parameter.parameterName)),
HttpStatus.BAD_REQUEST,
)
}
@ExceptionHandler(ValidationException::class)
fun handleCustomValidationExceptions(
ex: ValidationException,
): ResponseEntity<Map<String, Map<String, List<String>>>> {
val errors: MutableMap<String, List<String>> = HashMap()
for (validationError in ex.validationErrors) {
errors[validationError.message.code] = Arrays.asList(*validationError.parameters)
}
return ResponseEntity(
Collections.singletonMap<String, Map<String, List<String>>>(ValidationErrorType.CUSTOM_VALIDATION.name, errors),
HttpStatus.BAD_REQUEST,
)
}
@ExceptionHandler(BindException::class)
fun handleBindExceptions(ex: BindException): ResponseEntity<MutableMap<String, Map<String, String>>> {
val errors: MutableMap<String, String> = HashMap()
ex.bindingResult.allErrors.forEach { error: ObjectError ->
val fieldName = (error as FieldError).field
val errorMessage = error.defaultMessage
errors[fieldName] = errorMessage ?: ""
}
return ResponseEntity(
Collections.singletonMap(ValidationErrorType.STANDARD_VALIDATION.name, errors),
HttpStatus.BAD_REQUEST,
)
}
@ExceptionHandler(MissingServletRequestParameterException::class)
fun handleMissingServletRequestParameterException(
ex: MissingServletRequestParameterException,
): ResponseEntity<Map<String, Map<String, String?>>> {
val errors = Collections.singletonMap(ex.parameterName, ex.message)
return ResponseEntity(
Collections.singletonMap(ValidationErrorType.STANDARD_VALIDATION.name, errors),
HttpStatus.BAD_REQUEST,
)
}
@ExceptionHandler(MissingServletRequestPartException::class)
fun handleMissingServletRequestPartException(
ex: MissingServletRequestPartException,
): ResponseEntity<Map<String, Map<String, String?>>> {
val errors = Collections.singletonMap(ex.requestPartName, ex.message)
return ResponseEntity(
Collections.singletonMap(ValidationErrorType.STANDARD_VALIDATION.name, errors),
HttpStatus.BAD_REQUEST,
)
}
@ApiResponse(
responseCode = "400",
content = [
Content(
mediaType = "application/json",
schema =
Schema(
oneOf = [ErrorResponseTyped::class, ErrorResponseBody::class],
example = """{"code": "you_did_something_wrong", "params": ["something", "wrong"]}""",
),
),
],
)
@ApiResponse(
responseCode = "403",
content = [
Content(
mediaType = "application/json",
schema =
Schema(
oneOf = [ErrorResponseTyped::class, ErrorResponseBody::class],
example = """{"code": "operation_not_permitted", "params": ["translations.edit"]}""",
),
),
],
)
@ApiResponse(
responseCode = "401",
content = [
Content(
mediaType = "application/json",
schema =
Schema(
oneOf = [ErrorResponseTyped::class, ErrorResponseBody::class],
example = """{"code": "unauthenticated"}""",
),
),
],
)
@ExceptionHandler(ErrorException::class)
fun handleServerError(ex: ErrorException): ResponseEntity<ErrorResponseBody> {
logger.debug("Exception with response status {} caught", ex.httpStatus, ex)
return ResponseEntity(ex.errorResponseBody, ex.httpStatus)
}
@ExceptionHandler(EntityNotFoundException::class)
fun handleServerError(ex: EntityNotFoundException?): ResponseEntity<ErrorResponseBody> {
logger.debug("Entity not found", ex)
return ResponseEntity(ErrorResponseBody(Message.RESOURCE_NOT_FOUND.code, null), HttpStatus.NOT_FOUND)
}
@ApiResponse(
responseCode = "404",
content = [
Content(
mediaType = "application/json",
schema =
Schema(
oneOf = [ErrorResponseTyped::class, ErrorResponseBody::class],
example = """{"code": "resource_not_found", "params": null}""",
),
),
],
)
@ExceptionHandler(NotFoundException::class)
fun handleNotFound(ex: NotFoundException): ResponseEntity<ErrorResponseBody> {
logger.debug(ex.message, ex)
return ResponseEntity(ErrorResponseBody(ex.msg.code, null), HttpStatus.NOT_FOUND)
}
@ExceptionHandler(HttpMediaTypeNotSupportedException::class)
fun handleMediaTypeNotSupported(ex: HttpMediaTypeNotSupportedException): ResponseEntity<ErrorResponseBody> {
return ResponseEntity(
ErrorResponseBody(Message.UNSUPPORTED_MEDIA_TYPE.code, listOf(ex.contentType?.toString())),
HttpStatus.UNSUPPORTED_MEDIA_TYPE,
)
}
@ExceptionHandler(MaxUploadSizeExceededException::class)
fun handleFileSizeLimitExceeded(ex: MaxUploadSizeExceededException): ResponseEntity<ErrorResponseBody> {
return ResponseEntity(
ErrorResponseBody(Message.FILE_TOO_BIG.code, listOf()),
HttpStatus.BAD_REQUEST,
)
}
@ExceptionHandler(HttpMessageNotReadableException::class)
fun handleMessageNotReadable(ex: HttpMessageNotReadableException): ResponseEntity<ErrorResponseBody> {
val params = ex.rootCause?.message?.let { listOf(it) }
return ResponseEntity(
ErrorResponseBody(Message.REQUEST_PARSE_ERROR.code, params),
HttpStatus.BAD_REQUEST,
)
}
@ExceptionHandler(HttpRequestMethodNotSupportedException::class)
fun handleFileSizeLimitExceeded(ex: HttpRequestMethodNotSupportedException): ResponseEntity<Void> {
logger.debug(ex.message, ex)
return ResponseEntity(HttpStatus.METHOD_NOT_ALLOWED)
}
@ExceptionHandler(InvalidDataAccessApiUsageException::class)
fun handleFileSizeLimitExceeded(ex: InvalidDataAccessApiUsageException): ResponseEntity<ErrorResponseBody> {
Sentry.captureException(ex)
val contains = ex.message?.contains("could not resolve property", true) ?: false
if (contains) {
return ResponseEntity(
ErrorResponseBody(Message.UNKNOWN_SORT_PROPERTY.code, null),
HttpStatus.BAD_REQUEST,
)
}
throw ex
}
@ExceptionHandler(QueryException::class)
fun handleQueryException(ex: QueryException): ResponseEntity<ErrorResponseBody> {
if (ex.message!!.contains("could not resolve property")) {
return handleServerError(BadRequestException(Message.COULD_NOT_RESOLVE_PROPERTY))
}
throw ex
}
@ExceptionHandler(RateLimitedException::class)
fun handleRateLimited(ex: RateLimitedException): ResponseEntity<RateLimitResponseBody> {
logger.debug("Rate limited", ex)
return ResponseEntity(
RateLimitResponseBody(Message.RATE_LIMITED, ex.retryAfter, ex.global),
HttpStatus.TOO_MANY_REQUESTS,
)
}
@ExceptionHandler(RateLimitBlockedException::class)
fun handleRateLimitBlocked(ex: RateLimitBlockedException): ResponseEntity<Unit> {
logger.debug("Rate limit blocked (strike {})", ex.strikeCount)
return ResponseEntity.status(444).build()
}
@ExceptionHandler(NoResourceFoundException::class)
fun handleNoResourceFound(ex: NoResourceFoundException): ResponseEntity<ErrorResponseBody> {
logger.debug("No resource found", ex)
return ResponseEntity(
ErrorResponseBody(Message.RESOURCE_NOT_FOUND.code, listOf(ex.resourcePath)),
HttpStatus.NOT_FOUND,
)
}
fun handleBrokenPipe(ex: Throwable): ResponseEntity<ErrorResponseBody> {
logger.debug("Client aborted: ${ex.javaClass.simpleName}}: ${ex.message}")
return ResponseEntity(HttpStatus.BAD_GATEWAY)
}
@ExceptionHandler(Throwable::class)
fun handleOtherExceptions(ex: Throwable): ResponseEntity<ErrorResponseBody> {
if (ex is IOException && ex.message?.contains("Broken pipe") == true) {
return handleBrokenPipe(ex)
}
val rootCause = ExceptionUtils.getRootCause(ex)
if (rootCause is IOException && rootCause.message?.contains("Broken pipe") == true) {
return handleBrokenPipe(ex)
}
Sentry.captureException(ex)
logger.error(ex.stackTraceToString())
return ResponseEntity(
ErrorResponseBody(
"unexpected_error_occurred",
listOf(ex::class.java.name),
),
HttpStatus.INTERNAL_SERVER_ERROR,
)
}
@ExceptionHandler
fun handleTransactionExceptions(exception: TransactionSystemException): ResponseEntity<ErrorResponseBody> {
val rootCause = ExceptionUtils.getRootCause(exception)
if (rootCause is NotFoundException) {
return handleNotFound(rootCause)
}
if (rootCause is BadRequestException) {
return handleServerError(rootCause)
}
throw exception
}
@ExceptionHandler(ClientAbortException::class)
fun handleClientAbortException(
exception: ClientAbortException?,
request: HttpServletRequest,
) {
val message = "ClientAbortException generated by request {} {} from remote address {} with X-FORWARDED-FOR {}"
val headerXFF = request.getHeader("X-FORWARDED-FOR")
logger.warn(message, request.method, request.requestURL, request.remoteAddr, headerXFF)
}
}