I would recommend making the exception know its own error code, e.g. something like this:
public abstract class ApplicationException extends RuntimeException {
protected ApplicationException() {
super();
}
protected ApplicationException(String message) {
super(message);
}
protected ApplicationException(Throwable cause) {
super(cause);
}
protected ApplicationException(String message, Throwable cause) {
super(message, cause);
}
public abstract String getErrorCode();
public abstract HttpStatus getHttpStatus();
}
public class GeekAlreadyExistsException extends ApplicationException {
private static final long serialVersionUID = 1L;
public GeekAlreadyExistsException() {
super();
}
public GeekAlreadyExistsException(String message) {
super(message);
}
public GeekAlreadyExistsException(String message, Throwable cause) {
super(message, cause);
}
@Override
public String getErrorCode() {
return "geeks-1";
}
@Override
public HttpStatus getHttpStatus() {
return HttpStatus.BAD_REQUEST;
}
}
If you don't want the one-errorcode-per-exception constraint, you can instead pass the error code on the constructor call.
That still allows some specialized subclass exceptions to hardcode the error code, so the caller cannot specify it.
public class ApplicationException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final String errorCode;
private final HttpStatus httpStatus;
public ApplicationException(String errorCode, HttpStatus httpStatus) {
super();
this.errorCode = errorCode;
this.httpStatus = httpStatus;
}
public ApplicationException(String errorCode, HttpStatus httpStatus, String message) {
super(message);
this.errorCode = errorCode;
this.httpStatus = httpStatus;
}
public ApplicationException(String errorCode, HttpStatus httpStatus, Throwable cause) {
super(cause);
this.errorCode = errorCode;
this.httpStatus = httpStatus;
}
public ApplicationException(String errorCode, HttpStatus httpStatus, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
this.httpStatus = httpStatus;
}
public final String getErrorCode() {
return this.errorCode;
}
public final HttpStatus getHttpStatus() {
return this.httpStatus;
}
}
public class GeekAlreadyExistsException extends ApplicationException {
private static final long serialVersionUID = 1L;
public GeekAlreadyExistsException() {
super("geeks-1", HttpStatus.BAD_REQUEST);
}
public GeekAlreadyExistsException(String message) {
super("geeks-1", HttpStatus.BAD_REQUEST, message);
}
public GeekAlreadyExistsException(String message, Throwable cause) {
super("geeks-1", HttpStatus.BAD_REQUEST, message, cause);
}
}