Diagnostics
The TypeSpec compiler uses the diagnostic API to report errors and warnings in the specification.
Best practices
- ❌ Avoid using
throw
to report errors. Any exceptions thrown in this manner will be perceived as bugs in your library by the user. - ✅ Utilize the diagnostic API to report anticipated errors and warnings.
- ✅ Employ
reportDiagnostic
in a decorator,$onValidate
or$onEmit
- ❌ Refrain from using
reportDiagnostic
in an accessor (a function intended to be used in another library or emitter). Refer to the section on collecting diagnostics for more information.
- ✅ Employ
Diagnostic requirements
- Each diagnostic MUST have a
code
. The complete code is the library name followed by the declared code. (<lib-name>/<local-code>
) - Each diagnostic MUST have a
severity
. It can beerror
orwarning
. Errors cannot be suppressed. - Each diagnostic MUST have at least one message. Using
default
as themessageId
will make it the default selection. - Each diagnostic message MAY have parameters to interpolate information into the message.
How to use
Declare the diagnostics you plan to report
This will represent three different diagnostics with the full names of:
@typespec/my-lib/no-array
@typespec/my-lib/duplicate-route
@typespec/my-lib/duplicate-name
Report diagnostics
Collect diagnostics
When attempting to report a diagnostic in an accessor, a good practice is not to report the diagnostic to the program directly, but return a tuple to let the user decide what to do. This prevents duplicate diagnostics emitter if the accessor is called multiple times.
or manually