Files
c-api/src/main/java/com/mini/capi/exception/GlobalExceptionHandler.java
2025-09-22 22:16:27 +08:00

58 lines
2.1 KiB
Java

package com.mini.capi.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理业务异常
*/
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Map<String, String>> handleRuntimeException(RuntimeException e) {
log.error("业务异常:", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("code", "500", "msg", e.getMessage()));
}
/**
* 处理参数异常
*/
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Map<String, String>> handleIllegalArgumentException(IllegalArgumentException e) {
log.error("参数异常:", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("code", "400", "msg", e.getMessage()));
}
/**
* 处理附件过大异常
*/
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity<Map<String, String>> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
log.error("附件过大:", e);
return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE)
.body(Map.of("code", "413", "msg", "附件大小超过限制"));
}
/**
* 处理通用异常
*/
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, String>> handleException(Exception e) {
log.error("系统异常:", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("code", "500", "msg", "系统内部错误,请联系管理员"));
}
}