Search code examples
javaspringspring-bootexceptionspring-bean

Can I create an exception as a spring bean?


Can I create an spring bean which is a Java exception?

And then throw it multiple times ( lets say using different strings via setter)


Solution

  • Yes We can create. Sample code given below.

    @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);
        }
     }
    

    for Custom exception as below:

    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;
    }
    }