Коды состояния обработки исключений - PullRequest
2 голосов
/ 13 октября 2019

В моем проекте создана обработка исключений с использованием чего-то вроде подхода ниже. Я имею в виду, что мы добавляем новое GeekAlreadyExistsException () в некоторый уровень обслуживания, и, наконец, будет возвращен некоторый ответ об ошибке (в зависимости от кода ошибки).

public interface ErrorCode {

    String code();

    HttpStatus httpStatus();

}

enum GeeksApiErrorCodes implements ErrorCode {
    GEEK_ALREADY_EXISTS("geeks-1", HttpStatus.BAD_REQUEST);

    private final String code;
    private final HttpStatus httpStatus;

    GeeksApiErrorCodes(String code, HttpStatus httpStatus) {
        this.code = code;
        this.httpStatus = httpStatus;
    }

    @Override
    public String code() {
        return code;
    }

    @Override
    public HttpStatus httpStatus() {
        return httpStatus;
    }
}

Ответы [ 2 ]

2 голосов
/ 13 октября 2019

Отображение каждого кода ошибки с новым классом исключений не является хорошим решением. Если в будущем вам понадобится больше кодов ошибок, вам придется создавать еще больше классов. Поэтому лучшим решением будет заполнение кода ошибки только во время создания / создания исключения. Как показано ниже:

package test.file;

public class MyException extends RuntimeException {

  /**
   *
   */
  private static final long serialVersionUID = 1L;

  //The error code
  private final String errorCode;

  //The error message corresponding to the error code. Resolved on the basis of the Locale
  private final HttpStatus httpStatus;

  public MyException(final String errorCode, final HttpStatus httpStatus) {
    this.errorCode = errorCode;
    this.httpStatus = httpStatus;
  }

  public MyException(final String errorCode, final HttpStatus httpStatus, final Throwable cause) {
    super(cause);
    this.errorCode = errorCode;
    this.httpStatus = httpStatus;
  }

  public MyException(final String message, final String errorCode, final HttpStatus httpStatus, final Throwable cause) {
    super(message, cause);
    this.errorCode = errorCode;
    this.httpStatus = httpStatus;
  }

  /**
   * Method will return error code.
   *
   * @return
   */
  public String getErrorCode() {
    return errorCode;
  }

  /**
   * @return the httpStatus
   */
  public HttpStatus getHttpStatus() {
    return httpStatus;
  }

}

Здесь вы можете напрямую получить errorCode и выполнить соответствующее действие. Это выполнит ваше требование, что вы упомянули в вопросе. Это будет самое простое решение вашей проблемы.

2 голосов
/ 13 октября 2019

Я бы порекомендовал, чтобы исключение знало свой собственный код ошибки, например, что-то вроде этого:

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);
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...