Sass Error and Validation
Reject a spacing step that violates a small helper contract.
How it works
@error stops compilation with an explanatory message. Use it when continuing would emit misleading or invalid CSS. Our helper accepts only nonnegative unitless integers. It checks type before numeric operations so a string fails with the intended message. A clear rejection is part of a reusable helper API, just like the value returned for valid input.
Run the code
Use Dart Sass 1.107.0 in a separate learning folder. Install Node.js, then run npm install --save-dev --save-exact sass@1.107.0. Save every file below with its shown path. Run npx sass error-validation.scss error-validation.css --no-source-map from that folder. Browsers receive compiled CSS, not Sass.
The existing Sass playground uses legacy LibSass 3.6.2 and cannot run modern modules. The compiled CSS preview uses the isolated HTML/CSS editor; it does not compile Sass online. Preloading does not execute the preview. Apache, MySQL and PHP are not required.
Example
error-validation.scss
Download error-validation.scss — save at the shown relative path.
@use "sass:meta";
@use "sass:math";
@function step($n) {
@if meta.type-of($n) != "number" {
@error "Step must be a nonnegative unitless integer";
}
@if not math.is-unitless($n) or $n < 0 or math.floor($n) != $n {
@error "Step must be a nonnegative unitless integer";
}
@return $n * 4px;
}
.screening-card {
padding: step(3);
}
Expected CSS
.screening-card {
padding: 12px;
}
Three is valid and becomes 12px. The review also compiles calls with zero, a negative value, a fraction, a unit-bearing value and a string. Those cases distinguish an intentional contract from a helper that merely happens to work for one example.
Preview compiled CSS — choose Run code. Change and compile Sass locally first.
Check step(0), step(-1), step(1.5), step(2px) and step("3"). Zero returns 0px; the other four must stop compilation with the stated error.
Technical reference: official Sass documentation. Original fictional film-club examples; no booking service is provided.