ApplicationException.java

  1. package cn.home1.oss.lib.errorhandle.api;

  2. import static com.google.common.base.Preconditions.checkNotNull;

  3. import com.google.common.base.MoreObjects;

  4. import lombok.EqualsAndHashCode;
  5. import lombok.Getter;

  6. import org.springframework.http.HttpStatus;

  7. import java.io.Serializable;
  8. import java.util.Map;

  9. /**
  10.  * 应用抛出的通用错误信息.
  11.  *
  12.  * <p>
  13.  * Created by zhanghaolun on 16/7/1.
  14.  * </p>
  15.  */
  16. //@JsonInclude(JsonInclude.Include.NON_EMPTY) // for Jackson 2.x
  17. //@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) // for Jackson 1.x
  18. //@XmlRootElement(name = "applicationError") // for JAXB
  19. @EqualsAndHashCode(callSuper = false, of = {"status", "template"})
  20. @Getter
  21. public final class ApplicationException extends RuntimeException implements Serializable {

  22.   private static final long serialVersionUID = 1L;

  23.   private static final String APPLICATION_EXCEPTION = "application exception";

  24.   private final HttpStatus status;
  25.   private final String template;
  26.   private final Map<String, Serializable> contextVariables;

  27.   public ApplicationException( //
  28.     final HttpStatus status, //
  29.     final String template, //
  30.     final Map<String, Serializable> contextVariables //
  31.   ) {
  32.     super(APPLICATION_EXCEPTION);
  33.     this.status = checkNotNull(status, "status must not null");
  34.     this.template = checkNotNull(template, "template must not null");
  35.     this.contextVariables = checkNotNull(contextVariables, "contextVariables must not null");
  36.   }

  37.   public static Boolean isApplicationError(final Throwable throwable) {
  38.     return throwable != null && ApplicationException.class.isAssignableFrom(throwable.getClass());
  39.   }

  40.   public Map<String, Serializable> getContextVariables() {
  41.     return this.contextVariables;
  42.   }

  43.   public HttpStatus getStatus() {
  44.     return this.status;
  45.   }

  46.   public String getTemplate() {
  47.     return this.template;
  48.   }

  49.   @Override
  50.   public String toString() {
  51.     final MoreObjects.ToStringHelper toStringHelper = MoreObjects.toStringHelper(ApplicationException.class)
  52.       .add("status", this.status)
  53.       .add("template", this.template);
  54.     if (this.contextVariables != null) {
  55.       this.contextVariables.entrySet().forEach(entry -> toStringHelper.add(entry.getKey(), entry.getValue()));
  56.     }
  57.     return toStringHelper.toString();
  58.   }
  59. }