Server Errors
The NATS server sends -ERR protocol messages to a client when something goes wrong on the server side: a permission denial, an authentication problem, a client-level limit, and so on. The ServerError event on NatsConnection raises one of these messages every time the server emits one, so an application can observe them without scraping logs.
Subscribing to the Event
Hook the event the same way as any other connection event. The raw error text is on args.Error:
await using NatsConnection nc = new NatsConnection();
nc.ServerError += (sender, args) =>
{
Console.WriteLine($"Server error: {args.Error}");
return default;
};
Classifying the Error
args.Kind is parsed from the raw text and exposes the common server errors as a NatsServerErrorKind enum value. Anything the parser does not recognise stays as NatsServerErrorKind.Unknown; args.Error always carries the original text.
await using NatsConnection nc = new NatsConnection();
nc.ServerError += (sender, args) =>
{
switch (args.Kind)
{
case NatsServerErrorKind.PermissionsViolation:
Console.WriteLine($"Permission denied: {args.Error}");
break;
case NatsServerErrorKind.AuthorizationViolation:
case NatsServerErrorKind.AuthenticationExpired:
case NatsServerErrorKind.AuthenticationRevoked:
case NatsServerErrorKind.AccountAuthenticationExpired:
Console.WriteLine($"Auth problem: {args.Error}");
break;
default:
Console.WriteLine($"Server error ({args.Kind}): {args.Error}");
break;
}
return default;
};
The recognised kinds are:
PermissionsViolation- subscribe or publish denied for the connected userAuthorizationViolation- authorization failure during connectAuthenticationExpired- user authentication expiredAuthenticationRevoked- user authentication revokedAccountAuthenticationExpired- account authentication expiredStaleConnection- server timed out a stalled connectionMaximumConnectionsExceeded- server-wide connection limit reachedMaximumAccountConnectionsExceeded- per-account connection limit reachedMaximumSubscriptionsExceeded- per-connection subscription limit reached
The event fires for every -ERR line, including messages whose Kind is Unknown. Match on args.Error if the application needs to handle a server error not covered by the enum.