GlobalExceptionHandler.java 1.88 KB
package com.xly.erp.common.exception;

import com.xly.erp.common.response.ApiResponse;
import com.xly.erp.common.response.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /** REQ-USR-004 账号锁定专用:把 cooldownSeconds 暴露在 data.cooldownSeconds */
    @ExceptionHandler(AccountLockedException.class)
    public ApiResponse<java.util.Map<String, Object>> handleAccountLocked(AccountLockedException e) {
        log.warn("AccountLocked code={} cooldown={}s", e.getCode(), e.getCooldownSeconds());
        java.util.Map<String, Object> data = java.util.Map.of("cooldownSeconds", e.getCooldownSeconds());
        return new ApiResponse<>(e.getCode(), e.getMessage(), data, System.currentTimeMillis());
    }

    @ExceptionHandler(BizException.class)
    public ApiResponse<Void> handleBiz(BizException e) {
        log.warn("BizException code={} message={}", e.getCode(), e.getMessage());
        return ApiResponse.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<Void> handleValidation(MethodArgumentNotValidException e) {
        FieldError fe = e.getBindingResult().getFieldError();
        String detail = fe == null
                ? ErrorCode.PARAM_INVALID.getMessage()
                : fe.getField() + ": " + fe.getDefaultMessage();
        return ApiResponse.fail(ErrorCode.PARAM_INVALID, detail);
    }

    @ExceptionHandler(Exception.class)
    public ApiResponse<Void> handleAll(Exception e) {
        log.error("Uncaught exception", e);
        return ApiResponse.fail(ErrorCode.INTERNAL_ERROR);
    }
}