接口 ExceptionTranslator<E extends Exception>

类型参数:
E - The translated exception type.

Note, this generic type must be specified by any class implements this interface, otherwise, exception will be raised


public interface ExceptionTranslator<E extends Exception>
Exception translator for database exception, no matter it is low-level JDBC exception, such as SQLException; or a relatively advanced Jimmer exception, such as @SaveException.NotUnique

Example:


 new ExceptionTranslator<SaveException.NotUnique>() {
     @Override
     public @Nullable Exception translate(
             @NotNull SaveException.NotUnique exception,
             @NotNull Args args
     ) {
         if (exception.isMatched(BookProps.NAME, BookProps.EDITION)) {
             return new IllegalArgumentException(
                 "The book whose name is \"" +
                 exception.getValue(BookProps.NAME) +
                 "\" and edition is \"" +
                 exception.getValue(BookProps.EDITION) +
                 "\" already exists"
             );
         }
         return null;
     }
 }
 

After being translated, exceptions can continue to be translated until there is no matching translator. To avoid potential infinite recursion problems, the same translator will not be used twice.

If the final translated exception is RuntimeException, it will be thrown directly; otherwise, it will be wrapped and thrown as ExecutionException

There are 3 ways to setup exception translators.

  1. Add it to save command, like this
    
         sqlClient.getEntities()
              .saveCommand(...entity...)
              .addExceptionTranslator(
                  new ExceptionTranslator<SaveException.NotUnique>() {
                      ...
                  }
              )
         

    This configuration has a higher priority. If the same exception type is configured twice by this method and the global configuration, the configuration of this method takes precedence.

  2. Global configuration without spring-starter, like this
    
         JSqlClient sqlClient = JSqlClient
              .newBuilder()
              .addExceptionTranslator(
                  new ExceptionTranslator<SaveException.NotUnique>() {
                      ...
                  }
              )
         
  3. Global configuration by jimmer-spring-starter, by @Component of spring framework, such as
    
         @Component // Let spring know your translator
         public NotUniqueExceptionTranslator
             implements ExceptionTranslator<SaveException.NotUnique> {
             ...
         }