Expand description
Pretty-printable diagnostic reports for errors that reference GraphQL documents.
§Usage
To use pretty-printing in custom errors, implement the ToCliReport
trait.
use apollo_compiler::parser::SourceSpan;
use apollo_compiler::Schema;
use apollo_compiler::Name;
use apollo_compiler::diagnostic::CliReport;
use apollo_compiler::diagnostic::Diagnostic;
use apollo_compiler::diagnostic::ToCliReport;
/// Error type for a small GraphQL schema linter.
#[derive(Debug, thiserror::Error)]
enum LintError {
#[error("{name} should be PascalCase")]
InvalidCase { name: Name },
#[error("Missing @specifiedBy directive on scalar {name}")]
NoSpecifiedBy {
location: Option<SourceSpan>,
name: Name,
},
}
impl ToCliReport for LintError {
fn location(&self) -> Option<SourceSpan> {
match self {
LintError::InvalidCase { name } => name.location(),
LintError::NoSpecifiedBy { location, .. } => *location,
}
}
fn report(&self, report: &mut CliReport<'_>) {
match self {
LintError::InvalidCase { name } => {
report.with_label_opt(name.location(), "should be PascalCase");
report.with_help(format!("Try using {}", to_pascal_case(name)));
}
LintError::NoSpecifiedBy { location, .. } => {
report.with_label_opt(*location, "scalar does not have a specification");
}
}
}
}
The Diagnostic
type wraps errors that implement ToCliReport
and provides
the pretty-printing functionality. ToCliReport::to_diagnostic
returns a diagnostic
ready for formatting:
fn print_errors(schema: &Schema, errors: &[LintError]) {
for error in errors {
// Debug-formatting uses colors.
eprintln!("{:?}", error.to_diagnostic(&schema.sources));
}
}
Structs§
- CliReport
- A diagnostic report that can be printed to a CLI with pretty colors and labeled lines of GraphQL source code.
- Diagnostic
- An error bundled together with a source map, for conversion either to a pretty-printable CLI report or to a JSON-serializable GraphQL error.
Enums§
- Color
- Indicate when to use ANSI colors for printing.
Traits§
- ToCli
Report - Conversion to
CliReport