package ru.mtuci.messenger.web; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.ConstraintViolationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; 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.HandlerMethodValidationException; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.NoHandlerFoundException; import org.springframework.web.servlet.resource.NoResourceFoundException; import ru.mtuci.messenger.api.model.Error; import ru.mtuci.messenger.api.model.ErrorError; import ru.mtuci.messenger.exception.ApiException; import ru.mtuci.messenger.exception.UnauthorizedException; @RestControllerAdvice public class ApiAdvice { private static final Logger log = LoggerFactory.getLogger(ApiAdvice.class); @ExceptionHandler(ApiException.class) public ResponseEntity handleApi(HttpServletRequest request, HttpServletResponse response, ApiException exception) { log.info("api error code={}", exception.code().getValue()); String challenge = exception instanceof UnauthorizedException unauthorized ? unauthorized.challenge() : null; return response(request, response, exception.status(), exception.code(), exception.getMessage(), challenge); } @ExceptionHandler({ HttpMessageNotReadableException.class, MethodArgumentNotValidException.class, ConstraintViolationException.class, HandlerMethodValidationException.class, MethodArgumentTypeMismatchException.class, MissingServletRequestParameterException.class, HttpRequestMethodNotSupportedException.class }) public ResponseEntity handleInvalid(HttpServletRequest request, HttpServletResponse response, Exception exception) { log.info("invalid request type={}", exception.getClass().getSimpleName()); return response(request, response, HttpStatus.BAD_REQUEST, ErrorError.CodeEnum.INVALID_REQUEST, "Некорректный запрос", null); } @ExceptionHandler(HttpMediaTypeNotSupportedException.class) public ResponseEntity handleMedia(HttpServletRequest request, HttpServletResponse response) { return response(request, response, HttpStatus.UNSUPPORTED_MEDIA_TYPE, ErrorError.CodeEnum.UNSUPPORTED_MEDIA_TYPE, "Неподдерживаемый тип содержимого", null); } @ExceptionHandler({NoResourceFoundException.class, NoHandlerFoundException.class}) public ResponseEntity handleMissing(HttpServletRequest request, HttpServletResponse response) { return response(request, response, HttpStatus.NOT_FOUND, ErrorError.CodeEnum.NOT_FOUND, "Объект не найден", null); } @ExceptionHandler({DataAccessException.class, CannotCreateTransactionException.class}) public ResponseEntity handleDataAccess(HttpServletRequest request, HttpServletResponse response, Exception exception) { log.warn("data access failure type={}", exception.getClass().getSimpleName()); return response(request, response, HttpStatus.SERVICE_UNAVAILABLE, ErrorError.CodeEnum.UNAVAILABLE, "Сервис временно недоступен", null); } @ExceptionHandler(Exception.class) public ResponseEntity handleUnexpected(HttpServletRequest request, HttpServletResponse response, Exception exception) { log.error("unexpected failure type={}", exception.getClass().getName(), exception); return response(request, response, HttpStatus.INTERNAL_SERVER_ERROR, ErrorError.CodeEnum.INTERNAL_ERROR, "Внутренняя ошибка", null); } private ResponseEntity response(HttpServletRequest request, HttpServletResponse response, HttpStatus status, ErrorError.CodeEnum code, String message, String challenge) { String requestId = RequestIdFilter.id(request); response.setHeader(RequestIdFilter.HEADER, requestId); HttpHeaders headers = new HttpHeaders(); if (challenge != null) { headers.set(HttpHeaders.WWW_AUTHENTICATE, challenge); } return new ResponseEntity<>(new Error(new ErrorError(code, message, requestId)), headers, status); } }