Map<String,String> responseInfo = new HashTable<String,String>();
responseInfo.set("FE_PRC_BACK_001","TargetUri is not exist");
//responseInfo.set("FE_XREQ_002","Target Uri of XRequest is Empty.");
//responseInfo.set("FE_REQ_003","The processor flag is incorrect or the BusinessContext time out.");
FE_PRC_BACK_001这样的是错误码,TargetUri is not exist是错误信息,需要以键值对(JSON)的形式响应给浏览器
这时,JAVA端是应该以什么方式来罗列这些错误码和错误信息呢?常量?还是枚举类型?
String FE_PRC_BACK_001 = "TargetUri is not exist";
请教一下各位大神,你们的项目中都是怎么设计的?
There are the following 2 solutions:
1. Encapsulate it into an object, for example:
2. Use enumeration to implement it, as follows:
The implementation ideas of 1 and 2 are actually similar (the code ideas given by the questioner are also similar, the difference is only in the use of specific
DTO
还是通用的Map
), but there are the following points to pay attention to when using enumerations:Assume enumeration For example, Result exists in base-api, version 1.0.0, and there are projects A and B respectively. Project A depends on project B, and projects A and B both depend on base-api
1. If project B upgrades base-api to 1.0. 1. A new enumeration is added to Result, and an interface of project B returns this new enumeration. However, if project A does not upgrade the base-api, if the interface is called and the new enumeration is returned, enumeration, a deserialization exception will be reported because the newly added enumeration does not exist in the old version of base-api;
2. When serializing JSON, the default is to serialize the enumeration into an enumeration Variable name. If you want to serialize it into a custom format (for example, include msg), you need to customize a serializer.
If all error messages have been determined, they can be written in the program. It is easier to use enumerations than global constants. It is still quite painful to have global constants corresponding to error codes and messages.
I like Java’s enumerations the most, mainly because Java’s enumeration types can be extended, constructed, and rewritten
toString
… Because Java’s enumeration itself is an object, and the enumeration type itself is a special class .If your error message cannot be fixed, it may be added during the application process and saved in the database. Then you need to write a special set of management classes to handle it, and use HashTable or HashMap to implement it. But I guess your problem is not that complicated.
Put the wrong key in the java enumeration, and then put the mapping between the wrong key and the wrong information in an external file, such as the properties file. At runtime, just retrieve the error text from the file in real time based on the error enumeration key. Because errors do not occur often, there should be no problem reading error information in real time. Of course, you can also read all errors when the program starts. The information is read in and cached to improve performance.