@error

在编写接受参数的混入函数时,通常希望确保这些参数具有 API 预期的类型和格式。如果不符合预期,需要通知用户并停止混入/函数的运行。

Sass 通过 @error 规则使这变得很容易,其写法为 @error <表达式>。它会打印表达式的值(通常是一个字符串),并附带一个堆栈跟踪,指示当前混入或函数是如何被调用的。打印错误后,Sass 会停止编译样式表,并告诉运行系统发生了错误。

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 时的显示效果:

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