forked from mtusi2026/mtusi2026lab4
90 lines
4.7 KiB
Java
90 lines
4.7 KiB
Java
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<ErrorResponse> handleInvalid(InvalidRequestException ex, HttpServletRequest req) {
|
|
return error(HttpStatus.BAD_REQUEST, "invalid_request", ex.getMessage(), req);
|
|
}
|
|
|
|
@ExceptionHandler(UnauthorizedException.class)
|
|
public ResponseEntity<ErrorResponse> 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<ErrorResponse> handleNotFound(NotFoundException ex, HttpServletRequest req) {
|
|
return error(HttpStatus.NOT_FOUND, "not_found", ex.getMessage(), req);
|
|
}
|
|
|
|
@ExceptionHandler(ConflictException.class)
|
|
public ResponseEntity<ErrorResponse> handleConflict(ConflictException ex, HttpServletRequest req) {
|
|
return error(HttpStatus.CONFLICT, "conflict", ex.getMessage(), req);
|
|
}
|
|
|
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
|
public ResponseEntity<ErrorResponse> 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<ErrorResponse> handleMalformed(HttpMessageNotReadableException ex, HttpServletRequest req) {
|
|
return error(HttpStatus.BAD_REQUEST, "invalid_request", "Malformed JSON or invalid field type", req);
|
|
}
|
|
|
|
@ExceptionHandler(MissingRequestHeaderException.class)
|
|
public ResponseEntity<ErrorResponse> handleMissingHeader(MissingRequestHeaderException ex, HttpServletRequest req) {
|
|
// Мы не бросаем это явно, но если понадобится required=true в @RequestHeader
|
|
return error(HttpStatus.UNAUTHORIZED, "unauthorized", "Missing required header", req);
|
|
}
|
|
|
|
@ExceptionHandler(Exception.class)
|
|
public ResponseEntity<ErrorResponse> handleAll(Exception ex, HttpServletRequest req) {
|
|
// Не логируем stack trace в ответ; для отладки — в stdout
|
|
ex.printStackTrace();
|
|
return error(HttpStatus.INTERNAL_SERVER_ERROR, "internal_error", "Internal server error", req);
|
|
}
|
|
|
|
private ResponseEntity<ErrorResponse> 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<ErrorResponse> handleDataIntegrity(org.springframework.dao.DataIntegrityViolationException ex, HttpServletRequest req) {
|
|
return error(HttpStatus.CONFLICT, "conflict", "Resource already exists", req);
|
|
}
|
|
|
|
@ExceptionHandler(PayloadTooLargeException.class)
|
|
public ResponseEntity<ErrorResponse> handlePayloadTooLarge(PayloadTooLargeException ex, HttpServletRequest req) {
|
|
return error(HttpStatus.PAYLOAD_TOO_LARGE, "payload_too_large", ex.getMessage(), req);
|
|
}
|
|
|
|
@ExceptionHandler(UnsupportedMediaTypeException.class)
|
|
public ResponseEntity<ErrorResponse> handleUnsupportedMedia(UnsupportedMediaTypeException ex, HttpServletRequest req) {
|
|
return error(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "unsupported_media_type", ex.getMessage(), req);
|
|
}
|
|
} |