Spring MVC 在静态嵌套类上使用@ControllerAdvice是一种不好的做法吗?

kq4fsx7k  于 8个月前  发布在  Spring
关注(0)|答案(1)|浏览(103)

在我的应用程序中,我需要两个单独的ControllerAdvice注解类:其中一个处理特定的异常,另一个是一个默认处理程序,用于所有意外的异常。然而,它们共享一些自定义逻辑,用于从处理的异常构建ResponseEntity。
为了将代码保存在一个地方,并使共享逻辑对它们可用,我想将两个类作为静态嵌套类放入一个外部类中,如下所示:

public class ExceptionHandler {

  private static ResponseEntity handleError(Exception ex, String message){ 
    // shared exception handling 
  }
  
  @ControllerAdvice
  @Order(Ordered.HIGHEST_PRECEDENCE)
  static class SpecializedExceptionHandler {
    
    @ExceptionHandler
    ResponseEntity handleMyException(MyException ex){
      return handleError(ex, "Custom Exception");
    }
  }

  @ControllerAdvice
  static class DefaultExceptionHandler {
    
    @ExceptionHandler
    ResponseEntity handleAllOtherExceptions(Exception ex){
      return handleError(ex, "Other Exception");
    }
  }
}

这似乎很好,我自己也无法提出反对它的论点,所以也许你可以帮助我。

w9apscun

w9apscun1#

一般的智慧是代码单元(Java中的类)有一个单一的目的。虽然实现在技术上是单一的目的,但它们不必要地纠缠在同一个文件中共存。
最好把它们分开,像这样:

public interface BaseExceptionHandler {

    default ResponseEntity handleError(Exception ex, String message) { 
        // shared exception handling 
    }
}

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SpecializedExceptionHandler implements BaseExceptionHandler {
    
    @ExceptionHandler
    ResponseEntity handleMyException(MyException ex){
        return handleError(ex, "Custom Exception");
    }
}

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DefaultExceptionHandler implements BaseExceptionHandler {
    
    @ExceptionHandler
    ResponseEntity handleAllOtherExceptions(Exception ex){
        return handleError(ex, "Other Exception");
    }
}

这也消除了static的使用,使它们更常规。
如果你喜欢继承风格:

public abstract class BaseExceptionHandler {

    ResponseEntity handleError(Exception ex, String message) { 
        // shared exception handling 
    }
}

public class SpecializedExceptionHandler extends BaseExceptionHandler {
   ...

如果你更喜欢static方法风格:

public final class ExceptionHandlerUtils {

    public static ResponseEntity handleError(Exception ex, String message) { 
        // shared exception handling 
    }
}

public class SpecializedExceptionHandler extends BaseExceptionHandler {
    // impl uses ExceptionHandlerUtils.handleError()

相关问题