GlobalException.java 1.23 KB
package com.ruoyi.global;

import com.ruoyi.common.global.Result;
import com.ruoyi.common.global.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author 20412
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    /**
     * 处理sql完整性约束冲突
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<?> uniqSqlHandler(SQLIntegrityConstraintViolationException e){
        // 唯一完成性约束冲突
        if (e.getMessage().contains("Duplicate entry")){
            String[] args = e.getMessage().split(" ");
            String message = args[2] + "已存在";
            return Result.ERROR(message);
        }
        return Result.ERROR(e.getMessage());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public Result<?> userInfoIllegal(UsernameNotFoundException e){
        return Result.ERROR(e.getMessage()).code(ResultCode.CODE_401.getCode());
    }
}