Java custom error class sample code

  • 2020-04-01 02:13:12
  • OfStack

In the program, you need to throw an exception and then output the error message in the user interface.

One is to catch an exception at the last UI display in the program, and then display the corresponding ErrorMessage. Sometimes, the program needs to throw an exception for business logic reasons, so it needs to customize the exception.

How to centralize the exception messages to meet the requirements of multilingual language requires that these error messages be centralized.

Custom error messages.


public class MyException extends Exception
{
    private static final long serialVersionUID = 1L;
    private Type type;

    public MyException( Type type )
    {
        super();
        this.type = type;
    }
    public MyException( Throwable t, Type type )
    {
        super( t );
        this.type = type;
    }
    public String toString() {
        return super.toString() + "<" + getErrorType().getErrorCode() + ">";
    }

    public Type getErrorType()
    {
        return type;
    }

    public enum Type
    {
        //System error
        SYSTEM_ERROR( "99999" ),

        //User authentication error
        USER_AUTH( "03003" );

        private String errorCode;
        Type( String errorCode )
        {
            this.errorCode = errorCode;
        }
        public String getErrorCode()
        {
            return this.errorCode;
        }
    }
}

The error code is thrown here, and you can then get the error message for the resource file based on this error code.


Related articles: