@error

在编写带有参数的 混入函数 时,你通常希望确保这些参数具有 API 期望的类型和格式。如果不是,则需要通知用户并且你的 mixin/函数需要停止运行。

Sass 通过 @error 规则(写作 @error <expression>)使这一切变得简单。它打印 表达 的值(通常是一个字符串)以及指示如何调用当前 mixin 或函数的堆栈跟踪。一旦打印出错误,Sass 就会停止编译样式表并告诉正在运行它的任何系统发生了错误。

¥Sass makes this easy with the @error rule, which is written @error <expression>. It prints the value of the expression (usually a string) along with a stack trace indicating how the current mixin or function was called. Once the error is printed, Sass stops compiling the stylesheet and tells whatever system is running it that an error occurred.

Playground

SCSS Syntax

@mixin reflexive-position($property, $value) {
  @if $property != left and $property != right {
    @error "Property #{$property} must be either left or right.";
  }

  $left-value: if($property == right, initial, $value);
  $right-value: if($property == right, $value, initial);

  left: $left-value;
  right: $right-value;
  [dir=rtl] & {
    left: $right-value;
    right: $left-value;
  }
}

.sidebar {
  @include reflexive-position(top, 12px);
  //       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // Error: Property top must be either left or right.
}
Playground

Sass Syntax

@mixin reflexive-position($property, $value)
  @if $property != left and $property != right
    @error "Property #{$property} must be either left or right."


  $left-value: if($property == right, initial, $value)
  $right-value: if($property == right, $value, initial)

  left: $left-value
  right: $right-value
  [dir=rtl] &
    left: $right-value
    right: $left-value



.sidebar
  @include reflexive-position(top, 12px)
  //       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // Error: Property top must be either left or right.

错误和堆栈跟踪的确切格式因实现而异,并且还取决于你的构建系统。从命令行运行时,Dart Sass 中的样子如下:

¥The exact format of the error and stack trace varies from implementation to implementation, and can also depend on your build system. This is what it looks like in Dart Sass when run from the command line:

Error: "Property top must be either left or right."
  ╷
3 │     @error "Property #{$property} must be either left or right.";
  │     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵
  example.scss 3:5   reflexive-position()
  example.scss 19:3  root stylesheet