import 'dart:async' show TimeoutException; import 'error_reason.dart'; import 'transport/connection_state.dart'; /// The common kinds of failure an operator can act on. enum ErrorAdviceKind { notConnected, serverTooOld, permission, timeout } /// What to do about a failure, as one sentence, and the raw detail it came /// from (kept available behind the sentence, never replaced by it). typedef ErrorAdvice = ({ErrorAdviceKind kind, String sentence, String detail}); /// Maps a request failure (an exception or the message a controller kept) to /// a sentence saying what to do, or null when it is none of the common kinds /// (the raw message then stands on its own). ErrorAdvice? errorAdvice(Object? error) { if (error == null) return null; final detail = describeErrorReason(error, fallback: 'Unknown error'); final kind = errorAdviceKind(error); if (kind == null) return null; return (kind: kind, sentence: errorAdviceSentence(kind), detail: detail); } /// The failure's kind, from its type or its words. ErrorAdviceKind? errorAdviceKind(Object error) { if (error is NotConnectedError) return ErrorAdviceKind.notConnected; if (error is TimeoutException) return ErrorAdviceKind.timeout; if (error is ProtocolError && error.code == 'elevation_required') { return ErrorAdviceKind.permission; } final text = '$error'.toLowerCase(); if (_tooOld.hasMatch(text)) return ErrorAdviceKind.serverTooOld; if (_permission.hasMatch(text)) return ErrorAdviceKind.permission; if (_timeout.hasMatch(text)) return ErrorAdviceKind.timeout; if (_notConnected.hasMatch(text)) return ErrorAdviceKind.notConnected; return null; } String errorAdviceSentence(ErrorAdviceKind kind) => switch (kind) { ErrorAdviceKind.notConnected => 'Not connected to the server. Check the connection in Settings, then ' 'try again.', ErrorAdviceKind.serverTooOld => 'This server is too old for this feature. Update the Pipelines server, ' 'then try again.', ErrorAdviceKind.permission => 'The server refused this for lack of permission. Sign in again in ' 'Settings › Connection, then try again.', ErrorAdviceKind.timeout => 'The server did not answer in time. Check the connection, then try ' 'again.', }; final _tooOld = RegExp( r'unknown (command|message|request)|unsupported (command|message|request)', ); final _permission = RegExp( r'permission denied|unauthori[sz]ed|forbidden|not signed in|' r'sign-in required|authentication (required|failed)|elevation_required|' r'\b401\b|\b403\b', ); final _timeout = RegExp(r'timed out|timeout'); final _notConnected = RegExp( r'not connected|connection (closed|replaced|refused|lost|failed)|' r'websocket|failed host lookup|network is unreachable|no saved machine', );