springboot controller统一异常处理

@ControllerAdvice


@RestControllerAdvice //纯接口系统可以使用
我的系统只有api接口 使用了RestControllerAdvice
@RestControllerAdvice
public class BaseExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Result exception(Exception e) {
        //e.printStackTrace();
        //logger.error(String.valueOf(e.getLocalizedMessage()));
        if (e.getCause() != null) {
            if (e.getCause().toString().startsWith("java.sql.SQLIntegrityConstraintViolationException:")) {
                return Result.err(StatusCode.REP_ERR, "重复操作");
            }
        }

        if (e.toString().startsWith(NoLoginException.class.getName())) {
            //未认证
            return Result.err(StatusCode.LOGIN_ERR, e.getMessage());
        }

        if (e.toString().startsWith(NoPermissionException.class.getName())) {
            //权限不足
            return Result.err(StatusCode.ACCESS_ERR, e.getMessage());
        }

        if(e.toString().startsWith(ExpiredJwtException.class.getName())){
            return Result.err(StatusCode.LOGIN_ERR,"您的登录状态过期了请重新登录");
        }

        return Result.err(StatusCode.REMOTE_ERR, e.getMessage());
    }

}

 

posted @ 2020-10-21 17:03  荣超  阅读(490)  评论(0)    收藏  举报