How to dynamic generate Enum type from mysql in Java spring boot application?

Viewed 186

In my project,we want manage all REST APIs errorcodes in a Enum type,like the following code:

package com.example.util
public enum ErrorType{
  SUCCESS("0000", "success")
  PARAMS_EMPTY("3001", "params cannot be empty")
}

The problem we encounter is if we put the class into util package,everytime we add a new error type in business spring boot app,we'll need to modify,publish and recompile the app and util project.That would be hard to maintance the util package.Basically,we prefer to maintance a relatively stable utility package.

So we are considering if there is a way that we can generate Enum type dynamiclly,we can comfigure the error information in mysql in advance,then we can load them into enum type in application boot procedure.

I'm not sure is this a good idea to dynamic generate enum type in Java,or if there is a better solution for this problem.

3 Answers

You can't add or remove values from an enum. Enums are complete static enumerations.

If you need to handle variable values you need to work with a standard class.

For example you can have something like the following:

public Error {
   public static Error getByName(String name) {
        ....
   }

   public static Error getByCode(int code) {
        ....
   }
}

and use it as follow:

 Error myError404 = Error.getByCode(404);

Obviously this code gives you a lot of flexibility, but you cannot know in advance if a particular error code exists or not. And you can't use ide facilities related to enums.

Generating an enum would not be so useful I think, since part of the power of enums is that you can use them statically in your code - so then you have to update your code anyway.

How about adding a an exception handler to your util library that can be populated with error codes / description mappings from the database that can then translate errors/exceptions to response codes / error messages for your API? (just guessing you have an api here :-) )

Thanks for your reply,we finally decide to give up this idea.Dynamic generate an enum would not help,indeed it will add more complexity to our project,it's not a common use of enum. Instead of this,we predefine our main error type likes user_error,system_error and db_error,etc.The specific error information will be processed in the business service.

Related