0

目前,当我们在 spring-shell 提示符下触发“脚本”命令时,它会执行文件中存在的所有命令,即使其中一个引发了任何异常(除了ExitRequest)。我在下面的代码中找到了,它只是返回异常作为结果,并且仅当异常是类型Shell.evaluate(Input)时才停止应用程序。ExitRequest有没有办法只为“脚本”命令改变这种行为?

           try {
                    Object[] args = resolveArgs(method, wordsForArgs);
                    validateArgs(args, methodTarget);

                    return ReflectionUtils.invokeMethod(method, methodTarget.getBean(), args);
                }
                catch (UndeclaredThrowableException e) {
                    if (e.getCause() instanceof InterruptedException || e.getCause() instanceof ClosedByInterruptException) {
                        Thread.interrupted(); // to reset interrupted flag
                    }
                    return e.getCause();
                }
                catch (Exception e) {
                    return e;
                }
                finally {
                    Signals.unregister("INT", sh);
                }

重写“script”命令本身没有意义,因为此代码存在于“Script.java”之外。目前,我有 Overriden "script" 命令,然后用 global flag 包裹Shell.run(InputProvider)调用EXIT_ON_ERROR。然后我创建了一个方面来代理对任何自定义命令的调用。如果advice发现任何异常,它会抛出一个ExitRequestifEXIT_ON_ERROR标志为真,这会导致停止执行脚本文件中的其余命令。

我试过的代码片段

    @ShellMethod(value = "Read and execute commands from a file.")
    public void script(File file) throws IOException {
        CustomScript.EXIT_ON_ERROR.set(true);
        Reader reader = new FileReader(file);
        try (FileInputProvider inputProvider = new FileInputProvider(reader, parser)) {
            shell.run(inputProvider);
        }
        CustomScript.EXIT_ON_ERROR.set(false);
    }
    @Around("within(com.agilone.provisioner.shell.component..*)")
    public Object allCommands(ProceedingJoinPoint joinPoint) throws Throwable{
        String commandName = ...;
        String parameters = ...;
        }
        log.info("Executing command [{} {}]", commandName, parameters);
        try{
            return joinPoint.proceed();
        }catch(RuntimeException e){
            log.error("Command [{} {}] failed", commandName,parameters, e);
            if(CustomScript.EXIT_ON_ERROR.get()){
                CustomScript.EXIT_ON_ERROR.set(false);
                throw new ExitRequest();
            }
            throw e;
        }
        
    }


4

0 回答 0