package ru.mtusi.messenger.controller.controllerAdvice; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.ConstraintViolationException; import lombok.RequiredArgsConstructor; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingRequestHeaderException; 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 ru.mtusi.messenger.config.properties.RateLimitProperties; import ru.mtusi.messenger.dto.ErrorDTO; import ru.mtusi.messenger.dto.ErrorErrorDTO; import ru.mtusi.messenger.exception.*; @RestControllerAdvice @RequiredArgsConstructor public class GlobalExceptionHandler { private final RateLimitProperties limitProperties; private final ApiErrorFactory errors; @ExceptionHandler(InvalidRequestException.class) public ResponseEntity invalidRequest(InvalidRequestException e, HttpServletRequest req) { return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, e.getMessage(), req); } @ExceptionHandler(UnauthorizedException.class) public ResponseEntity unauthorized(UnauthorizedException e, HttpServletRequest req) { boolean isLogin = "/api/v1/auth/sessions".equals(req.getRequestURI()); String challenge = isLogin ? "Basic realm=\"messenger\", charset=\"UTF-8\"" : "Bearer realm=\"messenger\""; return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .header("WWW-Authenticate", challenge) .body(errors.error(ErrorErrorDTO.CodeEnum.UNAUTHORIZED, e.getMessage(), req)); } @ExceptionHandler(NotFoundException.class) public ResponseEntity notFound(NotFoundException e, HttpServletRequest req) { return respond(HttpStatus.NOT_FOUND, ErrorErrorDTO.CodeEnum.NOT_FOUND, e.getMessage(), req); } @ExceptionHandler(ConflictException.class) public ResponseEntity conflict(ConflictException e, HttpServletRequest req) { return respond(HttpStatus.CONFLICT, ErrorErrorDTO.CodeEnum.CONFLICT, e.getMessage(), req); } @ExceptionHandler(PayloadTooLargeException.class) public ResponseEntity payloadTooLarge(PayloadTooLargeException e, HttpServletRequest req) { return respond(HttpStatus.PAYLOAD_TOO_LARGE, ErrorErrorDTO.CodeEnum.PAYLOAD_TOO_LARGE, e.getMessage(), req); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity validation(MethodArgumentNotValidException e, HttpServletRequest req) { return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Validation failed", req); } @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity unreadable(Exception e, HttpServletRequest req) { return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Malformed request body", req); } @ExceptionHandler(MissingServletRequestParameterException.class) public ResponseEntity missingParam(Exception e, HttpServletRequest req) { return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Missing parameter", req); } @ExceptionHandler(MethodArgumentTypeMismatchException.class) public ResponseEntity typeMismatch(Exception e, HttpServletRequest req) { return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Invalid parameter type", req); } @ExceptionHandler(HttpMediaTypeNotSupportedException.class) public ResponseEntity mediaType(Exception e, HttpServletRequest req) { return respond(HttpStatus.UNSUPPORTED_MEDIA_TYPE, ErrorErrorDTO.CodeEnum.UNSUPPORTED_MEDIA_TYPE, "Unsupported media type", req); } @ExceptionHandler(HandlerMethodValidationException.class) public ResponseEntity methodValidation(Exception e, HttpServletRequest req) { return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Validation failed", req); } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public ResponseEntity methodNotAllowed(Exception e, HttpServletRequest req) { return respond(HttpStatus.METHOD_NOT_ALLOWED, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Method not allowed", req); } @ExceptionHandler(RateLimitedException.class) public ResponseEntity rateLimited(RateLimitedException e, HttpServletRequest req) { return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) .header("Retry-After", String.valueOf(limitProperties.retryAfterSeconds())) .body(errors.error(ErrorErrorDTO.CodeEnum.RATE_LIMITED, e.getMessage(), req)); } @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity constraint(ConstraintViolationException e, HttpServletRequest req) { return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Validation failed", req); } @ExceptionHandler(Exception.class) public ResponseEntity fallback(Exception e, HttpServletRequest req) { return respond(HttpStatus.INTERNAL_SERVER_ERROR, ErrorErrorDTO.CodeEnum.INTERNAL_ERROR, "Internal error", req); } @ExceptionHandler(ServiceUnavailableException.class) public ResponseEntity serviceUnavailable(ServiceUnavailableException e, HttpServletRequest req) { return respond(HttpStatus.SERVICE_UNAVAILABLE, ErrorErrorDTO.CodeEnum.UNAVAILABLE, e.getMessage(), req); } @ExceptionHandler({ CannotCreateTransactionException.class, DataAccessResourceFailureException.class }) public ResponseEntity dependencyUnavailable(Exception e, HttpServletRequest req) { return respond(HttpStatus.SERVICE_UNAVAILABLE, ErrorErrorDTO.CodeEnum.UNAVAILABLE, "Dependency unavailable", req); } @ExceptionHandler(DataAccessException.class) public ResponseEntity dataAccess(DataAccessException e, HttpServletRequest req) { return respond(HttpStatus.INTERNAL_SERVER_ERROR, ErrorErrorDTO.CodeEnum.INTERNAL_ERROR, "Database error", req); } @ExceptionHandler(MissingRequestHeaderException.class) public ResponseEntity missingHeader(MissingRequestHeaderException e, HttpServletRequest req) { return respond(HttpStatus.BAD_REQUEST, ErrorErrorDTO.CodeEnum.INVALID_REQUEST, "Missing header: " + e.getHeaderName(), req); } private ResponseEntity respond(HttpStatus status, ErrorErrorDTO.CodeEnum code, String message, HttpServletRequest req) { return ResponseEntity.status(status).body(errors.error(code, message, req)); } }