异常处理

主要利用springboot@RestControllerAdvice实现,根据框架需要拦截对应异常

core/exception

package com.cooljs.core.exception;

import com.cooljs.core.request.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理器
 */
@RestControllerAdvice
@Slf4j
public class CoolExceptionHandler {

    @ExceptionHandler(CoolException.class)
    public R handleRRException(CoolException e) {
        R r = new R();
        r.put("code", e.getCode());
        r.put("message", e.getMessage());

        return r;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return R.error("已存在该记录");
    }

    @ExceptionHandler(BadCredentialsException.class)
    public R handleBadCredentialsException(BadCredentialsException e) {
        log.error(e.getMessage(), e);
        return R.error("账户密码不正确");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return R.error("不支持该请求方式,请区分POST、GET等请求方式是否正确");
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public R handleIllegalArgumentException(IllegalArgumentException e) {
        log.error(e.getMessage(), e);
        return R.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error();
    }
}

示例

@Override
    public Object login(BaseSysLoginDto baseSysLoginDto) {
        // 1、检查验证码是否正确 2、执行登录操作
        String verifyCode = coolCache.get("verify:img:" + baseSysLoginDto.getCaptchaId(), String.class);
        if (StrUtil.isNotEmpty(verifyCode) && verifyCode.equals(baseSysLoginDto.getVerifyCode())) {
            UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(baseSysLoginDto.getUsername(), baseSysLoginDto.getPassword());
            Authentication authentication = authenticationManager.authenticate(upToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // 查询用户信息并生成token
            BaseSysUserEntity sysUserEntity = baseSysUserMapper.selectOne(Wrappers.<BaseSysUserEntity>lambdaQuery().eq(BaseSysUserEntity::getUsername, baseSysLoginDto.getUsername()));
            if (sysUserEntity.getStatus() == 0) {
                throw new CoolException("用户已禁用");
            }
            Long[] roleIds = baseSysPermsService.getRoles(sysUserEntity);
            Dict tokenInfo = Dict.create()
                    .set("roleIds", roleIds)
                    .set("username", baseSysLoginDto.getUsername())
                    .set("userId", sysUserEntity.getId())
                    .set("passwordVersion", sysUserEntity.getPasswordV());
            String token = jwtTokenUtil.generateToken(tokenInfo);
            String refreshToken = jwtTokenUtil.generateRefreshToken(tokenInfo);

            return Dict.create()
                    .set("token", token)
                    .set("expire", jwtTokenUtil.getExpire())
                    .set("refreshToken", refreshToken)
                    .set("refreshExpire", jwtTokenUtil.getRefreshExpire());
        } else {
            coolCache.del("verify:img:" + baseSysLoginDto.getCaptchaId());
            throw new CoolException("验证码不正确");
        }
    }

Last Updated: