Why does this article exist? I had a problem in my daily life. Listen to me slowly

scenario

I encapsulated a BaseResultEnum in the component; Used to define returned error codes and error messages.

UNKNOWN_EXCEPTION(500, "Unknown exception, please contact system administrator "),Copy the code

Business projects write similar enumerated classes. But return, must xxxResultEnum. Code, xxxResultEnum. Two parameters are passed in MSG. Because enumerations don’t inherit.

implementation

One day suddenly found that enumeration can be implemented interface. It would be nice if the upper layer defined a unified interface

Public interface IResultCode {/** * return code ** @return Integer */ Integer getCode(); /** * return message ** @return String */ String getMsg(); }Copy the code

Enumeration class

@Getter @AllArgsConstructor public enum BaseResultEnum implements IResultCode { / / = = = = = = = = = = = = = = = = = = = = = = = = global result enumeration = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = / / / * * * unknown exception * / UNKNOWN_EXCEPTION (500, "unknown anomaly, Please contact the system administrator "), / * * * SUCCESS * / SUCCESS (200), "successful"), / * * * business exceptions * / FAILURE (400, "a business exception"), / * * * * / was not found NOT_FOUND (404, "Service not found "); / / = = = = = = = = = = = = = = = = = = = = = = = = specific business custom exception = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = / / / / fixed code 100 began to suggest a business module, such as: 100001, 100002; /** * status code */ final Integer code; /** * final String MSG; }Copy the code

In this case. The business defines the error message in its own project

@get@allargsconstructor Public enum LearningResultEnum implements IResultCode {/** * not found */ LEARNING_NOT_FOUND(1001, "This learning was not found "); /** * status code */ final Integer code; /** * final String MSG; }Copy the code

The specific use

throw new LearningException(LearningResultEnum.LEARNING_NOT_FOUND); Public BaseException(IResultCode resultEnum) {super(resultenum.getmsg ()); this.msg = resultEnum.getMsg(); this.code = resultEnum.getCode(); }Copy the code