GlobalExceptionHandler.kt
/*
Copyright (C) 2026 Sber
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
In any derivative products, you must retain the information of
owner of the original code and provide clear attribution to the project
https://dochub.info
The use of this product or its derivatives for any purpose cannot be a secret.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Maintainers:
Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025
Contributors:
Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025
*/
package org.archtool.archloader.controller
import io.micrometer.tracing.Tracer
import jakarta.servlet.ServletException
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.archtool.archloader.controller.api.dto.ApiError
import org.archtool.archloader.exception.UserDataException
/**
* Глобальный обработчик исключений для всех контроллеров.
*/
@ControllerAdvice
class GlobalExceptionHandler(
private val tracer: Tracer
) {
private val log = LoggerFactory.getLogger(javaClass)
@ExceptionHandler(Exception::class)
fun handleGeneralException(ex: Exception): ResponseEntity<ApiError> {
log.error("Необработанное исключение: {}", ex.message, ex)
return ResponseEntity.internalServerError()
.body(
ApiError(
status = HttpStatus.INTERNAL_SERVER_ERROR.value(),
error = "Internal Server Error",
message = "Произошла непредвиденная ошибка. Попробуйте позже.",
traceId = tracer.currentSpan()?.context()?.traceId() ?: "not set"
)
)
}
@ExceptionHandler(UserDataException::class)
fun handleGeneralException(ex: UserDataException): ResponseEntity<ApiError> {
log.debug("Ошибка в запросе пользователя {}", ex.message, ex)
return ResponseEntity.badRequest()
.body(ex.toApiError())
}
@ExceptionHandler(ServletException::class)
fun handleGeneralException(ex: ServletException): ResponseEntity<ApiError> {
log.debug("Ошибка в запросе пользователя, до попадания в контроллер {}", ex.message, ex)
return ResponseEntity.badRequest()
.body(
ApiError(
status = HttpStatus.BAD_REQUEST.value(),
error = "Bad request",
message = ex.message ?: "Bad request",
traceId = tracer.currentSpan()?.context()?.traceId() ?: "not set"
)
)
}
}