GlobalExceptionHandler.java 1.34 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 {

    @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);
    }
}