我可以创建异常作为 spring bean 吗?[已结束]

Can I create an exception as a spring bean? [closed]

提问人:J.J. Beam 提问时间:10/11/2023 更新时间:10/11/2023 访问量:72

问:


想改进这个问题吗?通过编辑这篇文章添加详细信息并澄清问题。

上个月关闭。

我可以创建一个 Java 异常的 spring bean 吗?

然后多次抛出它(比如说通过 setter 使用不同的字符串)

java spring-boot 异常 spring-bean

评论

1赞 Jorn 10/11/2023
我认为没有理由 bean 不能扩展 Exception。你为什么不试试呢?
3赞 Jorn 10/11/2023
此外,多次抛出同一个 Exception 实例可能会为您提供不正确的堆栈跟踪信息。但这是可能的(而且是个坏主意)。
1赞 Andrew S 10/11/2023
如果消息是通过 setter 更新的,那么它就不是线程安全的。

答:

-1赞 Partha Sai 10/11/2023 #1

是的,我们可以创造。示例代码如下。

@Configuration
public class AppConfig {

    @Bean
    public MyCustomException myCustomException() {
        return new MyCustomException("This is a Spring-managed exception.");
    }
}

public class MyCustomException extends RuntimeException {
    public MyCustomException(String message) {
        super(message);
    }
 }

对于自定义异常,如下所示:

public class MyCustomException extends RuntimeException {
public MyCustomException(String message) {
    super(message);
}

public void setCustomMessage(String message) {
    // This is a bit hacky, but demonstrates the concept
    this.setStackTrace(this.getStackTrace());
    this.initCause(null);
    this.suppressedExceptions.clear();
    super.fillInStackTrace();
    
    try {
        Field detailMessage = Throwable.class.getDeclaredField("detailMessage");
        detailMessage.setAccessible(true);
        detailMessage.set(this, message);
    } catch (Exception e) {
        throw new RuntimeException("Failed to set custom message.", e);
    }
}
}
@Configuration
public class AppConfig {

@Bean
public MyCustomException myCustomException() {
    return new MyCustomException("Initial message.");
}
}


@Service
public class SomeService {
@Autowired
private MyCustomException myCustomException;

public void someMethod() {
    myCustomException.setCustomMessage("New message.");
    throw myCustomException;
}
}

评论

5赞 f1sh 10/11/2023
这不是一个好建议,甚至不是一个好主意。这根本不是线程安全的。它带来的问题比重用同一实例的好处要多得多。