package ru.mtusi.messenger.exception; import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingRequestHeaderException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import ru.mtusi.messenger.dto.ErrorResponse; import ru.mtusi.messenger.filter.RequestIdFilter; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(InvalidRequestException.class) public ResponseEntity handleInvalid(InvalidRequestException ex, HttpServletRequest req) { return error(HttpStatus.BAD_REQUEST, "invalid_request", ex.getMessage(), req); } @ExceptionHandler(UnauthorizedException.class) public ResponseEntity handleUnauthorized(UnauthorizedException ex, HttpServletRequest req) { String requestId = (String) req.getAttribute(RequestIdFilter.REQUEST_ID_ATTR); ErrorResponse body = ErrorResponse.of("unauthorized", ex.getMessage(), requestId); // Контракт требует заголовок WWW-Authenticate return ResponseEntity.status(HttpStatus.UNAUTHORIZED) .header("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"") .body(body); } @ExceptionHandler(NotFoundException.class) public ResponseEntity handleNotFound(NotFoundException ex, HttpServletRequest req) { return error(HttpStatus.NOT_FOUND, "not_found", ex.getMessage(), req); } @ExceptionHandler(ConflictException.class) public ResponseEntity handleConflict(ConflictException ex, HttpServletRequest req) { return error(HttpStatus.CONFLICT, "conflict", ex.getMessage(), req); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity handleValidation(MethodArgumentNotValidException ex, HttpServletRequest req) { String message = ex.getBindingResult().getFieldErrors().stream() .findFirst() .map(fe -> fe.getField() + ": " + fe.getDefaultMessage()) .orElse("Validation failed"); return error(HttpStatus.BAD_REQUEST, "invalid_request", message, req); } @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity handleMalformed(HttpMessageNotReadableException ex, HttpServletRequest req) { return error(HttpStatus.BAD_REQUEST, "invalid_request", "Malformed JSON or invalid field type", req); } @ExceptionHandler(MissingRequestHeaderException.class) public ResponseEntity handleMissingHeader(MissingRequestHeaderException ex, HttpServletRequest req) { // Мы не бросаем это явно, но если понадобится required=true в @RequestHeader return error(HttpStatus.UNAUTHORIZED, "unauthorized", "Missing required header", req); } @ExceptionHandler(Exception.class) public ResponseEntity handleAll(Exception ex, HttpServletRequest req) { // Не логируем stack trace в ответ; для отладки — в stdout ex.printStackTrace(); return error(HttpStatus.INTERNAL_SERVER_ERROR, "internal_error", "Internal server error", req); } private ResponseEntity error(HttpStatus status, String code, String message, HttpServletRequest req) { String requestId = (String) req.getAttribute(RequestIdFilter.REQUEST_ID_ATTR); return ResponseEntity.status(status).body(ErrorResponse.of(code, message, requestId)); } @ExceptionHandler(org.springframework.dao.DataIntegrityViolationException.class) public ResponseEntity handleDataIntegrity(org.springframework.dao.DataIntegrityViolationException ex, HttpServletRequest req) { return error(HttpStatus.CONFLICT, "conflict", "Resource already exists", req); } @ExceptionHandler(PayloadTooLargeException.class) public ResponseEntity handlePayloadTooLarge(PayloadTooLargeException ex, HttpServletRequest req) { return error(HttpStatus.PAYLOAD_TOO_LARGE, "payload_too_large", ex.getMessage(), req); } @ExceptionHandler(UnsupportedMediaTypeException.class) public ResponseEntity handleUnsupportedMedia(UnsupportedMediaTypeException ex, HttpServletRequest req) { return error(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "unsupported_media_type", ex.getMessage(), req); } }