Home > front end >  Good Code to return Error Category based on Error Code received
Good Code to return Error Category based on Error Code received

Time:07-20

I am lacking behind a creativity where, I am not sure, this is a good design to fetch the error Code from Exception received and then fetch the definite error Category based on that.

I want to return an error category based on the error Code i received from Exception and parse to another method , What is the best way I can try to do it ?

Input of Exception :

  1. You have got the error. [ErrorCode: 400 XYZ]
  2. You got error which has no errorCode

Code :

public class Program {
    try {

someFunction (x) ;

} catch (Exception e ) {

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String message = sw.toString();
Matcher m = Pattern.compile(".*:\\s (.*)\\s \\[ErrorCode: (\\d )").matcher(message);
if (m.find()) {
  String errorMessage = m.group(1); // You have got the error.
  String errorCode = m.group(2); // 400
// Here I want to fetch the error Category based on the errorCode
  String errorCategory = XYZ.errorCategory(errorCode);

`//Based on` the errorCode, errorCategory of INVALID_TEMPLATE which is an enum must be returned
SomeOtherFunc(errorCategory,errorMessage);



}

}

public class XYZ{

private static final Map<String,String> errorMap = new HashMap<>();

    public void populateErrorMap(){
        errorMap.put("400", INVALID_TEMPLATE(400, 400));
        errorMap.put("404", REQUEST_REJECTED(404, 404));


}
        


    }

    public static String errorCategory(String errorCode){
        return errorMap.get(errorCode);
    }

Output :

For Input 1, error Category i need : INVALID_TEMPLATE
For Input 2, error Category ( which doesn't have error Code from exception) i need by reading the exception message which will come : NO_ERROR_CODE

How to achieve this and what can be the good design ?

Also, what if there is no errorCode , and if i want to read by errorMessage , what can be the example to achieve this?

For ex : Exception came as : "You got error which has no errorCode".

I need to map this errorMessage with a possible errorCategory, like "NO_ERROR_CODE", how can i achieve this?

CodePudding user response:

I am not sure if I understood your issue properly
If you want to transform your exception code to a custom category this looks shorter:

Map<Integer, String> errorMap = new HashMap<Integer, String>();
errorMap.put(400, "INVALID_TEMPLATE");
errorMap.put(404, "REQUEST_REJECTED");
public static void ThrowsAnExceptionThenCallsFunction(){
    try {
        someFunction (x) ;
    } catch (Exception e ) {
        SomeOtherFunction(errorMap.get(e.getStatusCode()),errorMessage);
    }
}

Otherwise, you could add multiple catches for each exception type if you want to call different functions.

try {
    someFunction (x) ;
} catch (IllegalArgumentException e ) {
    // do this if exception 1
    callThisFunction1()
} catch (IndexOutOfBoundsException e ) {
    // do this if exception 2
    callThisFunction2()
} catch(ExceptionType3 | Exceptiontype4 ex) {
   // do this if exception 3 or 4
    callThisFunction3()
}

Also please try to write down your questions better, like give it a proper order.

1)your input
2)your desired output
3)your code
4)the issue

Thank you...

CodePudding user response:

In real life there are two audiences:

  • the log handler with a configurable log level (ERROR) and logging (in English) with much info;
  • the end user with an localized translated message, also with parameters.

The first property is that you probably want a message as format String with Object... parameters. Probably should use MessageFormat.

Sensible would be to support typed parameters.

/** Type-checkable Message Definition. */
public record MessageDef(String format, Class<?>... parameterTypes) {
    public void checkFormat() {
        ... check actual parameters with parameterTypes.length
    }
    public void checkUsage(Object[] args) {
        ... check parameter types
    }
}

One could make an enum for the error categories. However enums are more suitable for closed domains with a fixed set of values. Extending values in future means that you have created a needless common bottleneck for source version control and so on. An error is more like an open domain. However if you number them with error codes, an enum gives a nice overview.

The only advantage of error codes is the internationalisation. An Hungarian error message can be easily retrieved.

Then, if you rethrow check exceptions as RuntimeException, like IllegalArgumentException or you own custom ones, you might not want parallel classes: run-time exceptions and categories.

All-in-all I would advise an enum:

public enum MessageType {
    INVALID_TEMPLATE(400, Level.ERROR,
        new MessageDef("You have got the error in {0}.", String.class)),
    ...
    REQUEST_REJECTED(200, Level.INFO,
        new MessageDef("Done."));

    public final int code;
    public final Level level;
    public final MessageDef def;

    MessageType(int code, Level level, MessageDef def) {
        this.code = code;
        this.level = level;
        this.def = def;
    }
}

One small remark: such little discussion points in the beginning of a project sometimes might be better postponed to a fast refactoring after having written sufficient code. Here an enum might not fit, you might have much re-throwing of exceptions. A premature decision is not needed. And might hamper fast productivity. Especially as you probably need not mark the code places, you most likely call the same show-error dialog.

  •  Tags:  
  • java
  • Related