api/src/main/java/com/lyxh/api/docking/exception/GlobalExceptionHandler.java

47 lines
2.0 KiB
Java

package com.lyxh.api.docking.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) {
String msg = ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + ": " + e.getDefaultMessage())
.reduce((a, b) -> a + "; " + b)
.orElse("validation failed");
return ResponseEntity.badRequest()
.body(new ErrorResponse("400", msg));
}
@ExceptionHandler(ApiCallException.class)
public ResponseEntity<ErrorResponse> handleApiCall(ApiCallException ex) {
log.warn("API call error: code={} message={}", ex.getCode(), ex.getMessage());
HttpStatus status = switch (ex.getCode()) {
case "NETWORK_ERROR" -> HttpStatus.SERVICE_UNAVAILABLE;
case "HTTP_ERROR" -> HttpStatus.BAD_GATEWAY;
default -> HttpStatus.BAD_GATEWAY;
};
String detail = ex.getResponseBody() != null && !ex.getResponseBody().isEmpty()
? ex.getResponseBody() : ex.getMessage();
return ResponseEntity.status(status)
.body(new ErrorResponse(String.valueOf(status.value()), detail));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneral(Exception ex) {
log.error("Unexpected error", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(new ErrorResponse("500", "Internal server error"));
}
}