I am developing a Micro Service which is going to be called/used internally. I'm trying to improve error handling, but got confused with two below approaches.
- Having multiple exception classes for every layer (Business, Rest Client, Mapper etc)
- Creating one general exception class with specific error codes (Business, Rest, Mapper etc).
We tried first approach now, but it seems not that good. I see redundancy and violating DRY principle. Everything is similar except Status Code
.
Besides, I think for every case if we want to create a separate exception class (Of course extending parent
), it will lead to class explosion.
Some people says: first approach helps with better support and maintenance, but I think with specific error codes and adding more context to the exception and response, it will be easily supportable.
Below is what I think of the second approach:
Error Code Model
public class ErrorCode {
private int statusCode;
private String errorCode;
private String message;
}
Error Codes
public abstract class ErrorCodes {
public static ErroCode BAD_REQUEST = new ErrorCode (400, 10101, "Bad Request");
//Adding other error codes as well
}
Please Note that we can use enum for error codes.
Exception Class
public class CustomException extends Exception{
private ErrorCode errorCode;
private String description;
public CustomException (ErrorCode errorCode, Throwable throwable, String description){
//Constructor
}
public JsonObject asJson() {
return Json.createObjectBuilder()
.add("StatusCode", errorCode.getStatusCode())
.add("Message", errorCode.getMessage())
.add("Description", getDescription())
.build();
}
}
I thought we can handle every kind of exception, and throw a CustomException with specific error code and add more context to it.
Also it is much cleaner in Controller/Resource class to create the error response.
Please help me figure it out.
Thanks