Я бы порекомендовал, чтобы исключение знало свой собственный код ошибки, например, что-то вроде этого:
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;
}
}
Если вы не хотите ограничение одного кода ошибки на исключениевместо этого вы можете передать код ошибки при вызове конструктора.
Это все еще позволяет некоторым исключениям специализированных подклассов жестко закодировать код ошибки, поэтому вызывающая сторона не может его указать.
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);
}
}