# ExceptionInterpreter 异常解释

MornBoot可以对常见异常进行转义处理,当执代码行异常时,将异常信息转义为友好的提示信息。主要用于将异常信息输出给开发人员、系统日志、前端系统等,而不适合暴露给用户,但在极端情况下,用户看到转义后的异常消息,也比原始异常要友好很多。

Since:v1.0.0

当前支持

# 必要配置

Maven

<!--支持更多异常转义-->
<dependency>
  <groupId>site.morn.boot</groupId>
  <artifactId>morn-boot-interpreter</artifactId>
  <version>${morn.version}</version>
</dependency>

在JavaWeb项目中,MornBoot通常会自动捕获异常进行转义处理。因此开发者无需关注异常捕获的过程,只需要关注转义机制和扩展方式。

# 异常转义

注入服务

/**
 * 异常转义服务
 */
@Autowired
private ExceptionInterpreterService interpreterService;

将异常转义为应用消息

// BindException e;
ApplicationMessage am = interpreterService.interpret(e);
// ApplicationMessage(code=validate, message=username must not be null, solution=null)

ExceptionInterpreter在项目中的实际效果,可以参考ParamsValidation

# 扩展转义

MornBoot支持自由扩展转义池,在以下场景中,可能需要进行扩展。

  • 某异常出现得较为频繁,在业务代码中大量try/catch
  • 业务代码外发生的异常

以下是扩展案例:

  1. 使用@Target指定需转义的异常类型
  2. 返回ApplicationMessage类型消息
@Target(ConstraintViolationException.class)
public class ValidationExceptionInterpreter implements ExceptionInterpreter {

  @Override
  public ApplicationMessage interpret(Throwable throwable, Object... args) {
    ConstraintViolationException exception = GenericUtils.castFrom(throwable);
    List<String> messages = exception.getConstraintViolations().stream()
        .map(constraintViolation -> {
          String objectName = constraintViolation.getRootBean().getClass().getSimpleName(); // 对象名称
          String propertyName = constraintViolation.getPropertyPath().toString(); // 属性名称
          String message = constraintViolation.getMessage(); // 校验消息
          return String.format("%s.%s%s", objectName, propertyName, message);
        }).collect(Collectors.toList());
    return ApplicationMessages
        .buildMessage("validation.reject", StringUtils.collectionToCommaDelimitedString(messages),
            "");
  }
}

MornBoot通常会自动进行异常转义,在扩展转义池后,无需进行其它步骤。常见用法参考RestResponse