Exception Handling
Documentation menu
Every external call can fail. These notes describe the exceptions the service exposes and the way to handle them without hiding the cause.
Exceptions to expect
| Exception | When it is thrown |
|---|---|
ArgumentNullException | A required argument, such as the code or module source, is null. |
ArgumentException | A language alias is not valid for the highlighter. |
InvocationException | JavaScript or Node.js reports an error during the invocation. |
ObjectDisposedException | The service has been disposed and a call is made afterwards. |
OperationCanceledException | The cancellation token passed to the call is cancelled. |
Handling them well
Catch the specific exception you can act on. Log the original message and the input that caused it, without logging secrets or the full contents of a user document. Let unexpected exceptions reach the host so they are visible in telemetry.
try
{
var html = await service.HighlightAsync(code, alias, cancellationToken);
return html;
}
catch (ArgumentException)
{
return "<pre>" + WebUtility.HtmlEncode(code) + "</pre>";
}
Disposal
Resolve the service once for the lifetime of the host. Do not create a service for each request and dispose it afterwards, because each instance starts a Node.js process. Dispose the shared instance during application shutdown.