异常解决
未处理的异常将冒泡到 shell 的ResultHandlerService
然后最终
由ResultHandler
.链ExceptionResolver
实现
可用于解决异常,并为您提供返回消息的灵活性
与 Exit 代码一起放入 console 中,退出代码包含在CommandHandlingResult
.CommandHandlingResult
可能包含消息和/或退出代码。
static class CustomExceptionResolver implements CommandExceptionResolver {
@Override
public CommandHandlingResult resolve(Exception e) {
if (e instanceof CustomException) {
return CommandHandlingResult.of("Hi, handled exception\n", 42);
}
return null;
}
}
CommandExceptionResolver
实现可以全局定义为 bean。
@Bean
CustomExceptionResolver customExceptionResolver() {
return new CustomExceptionResolver();
}
或定义CommandRegistration
如果它仅适用于特定命令本身。
CommandRegistration.builder()
.withErrorHandling()
.resolver(new CustomExceptionResolver())
.and()
.build();
使用命令定义的解析程序在全局解析程序之前处理。 |
使用你自己的异常类型,它也可以是 boot 的ExitCodeGenerator
如果
您希望在此处定义退出代码。
static class CustomException extends RuntimeException implements ExitCodeGenerator {
@Override
public int getExitCode() {
return 0;
}
}
一些内置CommandExceptionResolver
bean 注册为处理常见的
命令解析引发的异常。这些 Cookie 使用 中定义的 Order presedence 进行注册CommandExceptionResolver.DEFAULT_PRECEDENCE
.
由于这些 bean 是按给定的顺序使用的,因此@Order
annotation 或Ordered
Interface from 可以像在任何其他 Spring 应用程序中一样使用。这
如果您需要控制自己的 bean 才能使用
在 defaults 之前或之后。