简体   繁体   English

如何在Spring Boot Java应用程序中提高自定义异常的可读性

[英]How to improve readability of custom exceptions in a Spring Boot Java application

We have a typical Spring Boot Java application with Services, Rest Controllers and Repositories. 我们有一个典型的带有服务,REST控制器和存储库的Spring Boot Java应用程序。

We use custom runtime exceptions in our services and controllers by re-throwing them from catch blocks and then handle them in a spring global exception handler (via @ControllerAdvice ). 我们通过从catch块中重新抛出它们,然后在spring全局异常处理程序中(通过@ControllerAdvice )处理它们,从而在服务和控制器中使用自定义的运行时异常。

Usually, we use throw new SomeCustomException("Message"); 通常,我们使用throw new SomeCustomException("Message"); construction, but it looks not so good to me as it's hard to see what exceptions are thrown throughout the code. 构造,但对我来说却不太好,因为很难看到整个代码中都抛出了什么异常。

Thinking of how I could improve readability of the code, I came up with the idea of creating static final instances and then use them like throw new SOME_CUSTOM_EXCEPTION; 考虑到如何提高代码的可读性,我想到了创建静态最终实例,然后像throw new SOME_CUSTOM_EXCEPTION;一样使用它们的throw new SOME_CUSTOM_EXCEPTION;

In this case, it is clear what exceptions class can throw and it is easy to check whether they are handled in the global exception handler. 在这种情况下,很明显可以抛出哪些异常类,并且很容易检查是否在全局异常处理程序中对其进行了处理。

I see some drawbacks with those constant exception instances though. 我看到那些常量异常实例有一些弊端。 First, what if need to pass an external exception into the custom exception, or there are multiple throws of the same class with different messages? 首先,如果需要将外部异常传递给自定义异常,或者同一类多次抛出不同消息,该怎么办?

Another idea is to extract exception messages as constants. 另一个想法是将异常消息提取为常量。 But again,sometimes we pass no messages. 但是,有时我们没有传递任何消息。

Are there best practices of indicating what exceptions a class can throw or I am over-thinking and it is just fine to throw new ? 是否有最佳实践来指示类可以抛出哪些异常,或者我考虑过多,并且可以throw new异常?

If you wanted to improve readability, perhaps additional custom exceptions with more detailed names would be enough. 如果您想提高可读性,也许其他具有更详细名称的自定义例外就足够了。 Additionally you could have a default message constructor, and store other common message strings inside the exception class as static constants: 另外,您可以具有默认的消息构造函数,并将其他常见消息字符串存储在异常类中作为静态常量:

public class CustomException {
    public static String ERROR_MESSAGE = "some error message";

    public CustomException() {
        super("Default message")
    }

    public CustomException(String message) {
        super(message)
    }
}

throw new CustomException(CustomException.ERROR_MESSAGE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM