Skip to content

Instantly share code, notes, and snippets.

@a7md0
Created May 2, 2022 19:17
Show Gist options
  • Save a7md0/f9d86754b1a5bbf622bb44cc29f6e3cd to your computer and use it in GitHub Desktop.
Save a7md0/f9d86754b1a5bbf622bb44cc29f6e3cd to your computer and use it in GitHub Desktop.
Custom HTTP exceptions with DioError factory constructor
final httpClient = Dio()..options.baseUrl = 'https://example.com';
try {
var response = await httpClient.post(
'/auth/signup',
data: values,
);
if (response.data == null) {
throw const EmptyResponseException(); // Manually throw the exception
}
} on DioError catch (e) {
throw HttpException.fromDio(e); // Throw the appropriate exception from the current DioError exception (The thrown exception will be of a type HttpException which can be handled appropriately)
}
import 'dart:io';
import 'package:dio/dio.dart';
abstract class HttpException implements Exception {
const HttpException();
factory HttpException.fromDio(DioError dioError) {
if (dioError.type == DioErrorType.connectTimeout) {
return const ConnectionTimeoutException();
} else if (dioError.type == DioErrorType.sendTimeout) {
return const SendTimeoutException();
} else if (dioError.type == DioErrorType.receiveTimeout) {
return const ReceiveTimeoutException();
} else if (dioError.type == DioErrorType.response) {
final response = dioError.response;
int statusCode = response!.statusCode!;
switch (statusCode) {
case 400:
return BadRequestException(response);
case 401:
return UnauthorizedException(response);
case 403:
return ForbiddenException(response);
case 404:
return NotFoundException(response);
case 405:
return MethodNotAllowedException(response);
case 406:
return NotAcceptableException(response);
case 407:
return ProxyAuthenticationRequiredException(response);
case 408:
return RequestTimeoutException(response);
case 409:
return ConflictException(response);
case 410:
return GoneException(response);
case 411:
return LengthRequiredException(response);
case 412:
return PreconditionFailedException(response);
case 413:
return PayloadTooLargeException(response);
case 414:
return UriTooLongException(response);
case 415:
return UnsupportedMediaTypeException(response);
case 416:
return RangeNotSatisfiableException(response);
case 417:
return ExpectationFailedException(response);
case 418:
return IamTeapotException(response);
case 428:
return PreconditionRequiredException(response);
case 429:
return TooManyRequestsException(response);
case 431:
return RequestHeaderFieldsTooLargeException(response);
case 451:
return UnavailableForLegalReasonsException(response);
case 500:
return InternalServerException(response);
case 501:
return NotImplementedException(response);
case 502:
return BadGatewayException(response);
case 503:
return ServiceUnavailableException(response);
case 504:
return GatewayTimeoutException(response);
case 505:
return HttpVersionNotSupportedException(response);
case 506:
return VariantAlsoNegotiatesException(response);
case 507:
return InsufficientStorageException(response);
case 508:
return LoopDetectedException(response);
case 510:
return NotExtendedException(response);
case 511:
return NetworkAuthenticationRequiredException(response);
default:
return UndefinedResponseException(response);
}
} else if (dioError.type == DioErrorType.cancel) {
return const CancelException();
} else if (dioError.type == DioErrorType.other) {
if (dioError.error != null && dioError.error is SocketException) {
return const NoConnectionException();
}
}
// DioErrorType.other // Default error type
return OtherException(dioError.error);
}
}
class NoConnectionException implements HttpException {
const NoConnectionException();
}
abstract class TimeoutException implements HttpException {
const TimeoutException();
}
class ConnectionTimeoutException implements TimeoutException {
const ConnectionTimeoutException();
}
class SendTimeoutException implements TimeoutException {
const SendTimeoutException();
}
class ReceiveTimeoutException implements TimeoutException {
const ReceiveTimeoutException();
}
class CancelException implements HttpException {
const CancelException();
}
class OtherException implements HttpException {
final dynamic error;
const OtherException(this.error);
}
class EmptyResponseException extends OtherException {
const EmptyResponseException() : super("Empty response");
}
abstract class ResponseException implements HttpException {
final int statusCode;
final String status;
final dynamic body;
ResponseException(Response<dynamic> response)
: body = response.data,
statusCode = response.statusCode ?? 0,
status = response.statusMessage ?? '';
}
class UndefinedResponseException extends ResponseException {
UndefinedResponseException(Response<dynamic> response) : super(response);
}
abstract class ClientException extends ResponseException {
ClientException(Response<dynamic> response) : super(response);
}
/// 400 Bad Request
///
/// The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
class BadRequestException extends ClientException {
BadRequestException(Response<dynamic> response) : super(response);
}
/// 401 Unauthorized
///
/// Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response.
class UnauthorizedException extends ClientException {
UnauthorizedException(Response<dynamic> response) : super(response);
}
/// 403 Forbidden
///
/// The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike 401 Unauthorized, the client's identity is known to the server.
class ForbiddenException extends ClientException {
ForbiddenException(Response<dynamic> response) : super(response);
}
/// 404 Not Found
///
/// The server can not find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 Forbidden to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web.
class NotFoundException extends ClientException {
NotFoundException(Response<dynamic> response) : super(response);
}
/// 405 Method Not Allowed
///
/// The request method is known by the server but is not supported by the target resource. For example, an API may not allow calling DELETE to remove a resource.
class MethodNotAllowedException extends ClientException {
MethodNotAllowedException(Response<dynamic> response) : super(response);
}
/// 406 Not Acceptable
///
/// This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent.
class NotAcceptableException extends ClientException {
NotAcceptableException(Response<dynamic> response) : super(response);
}
/// 407 Proxy Authentication Required
///
/// This is similar to 401 Unauthorized but authentication is needed to be done by a proxy.
class ProxyAuthenticationRequiredException extends ClientException {
ProxyAuthenticationRequiredException(Response<dynamic> response) : super(response);
}
/// 408 Request Timeout
///
/// This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.
class RequestTimeoutException extends ClientException {
RequestTimeoutException(Response<dynamic> response) : super(response);
}
/// 409 Conflict
///
/// This response is sent when a request conflicts with the current state of the server.
class ConflictException extends ClientException {
ConflictException(Response<dynamic> response) : super(response);
}
/// 410 Gone
///
/// This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code.
class GoneException extends ClientException {
GoneException(Response<dynamic> response) : super(response);
}
/// 411 Length Required
///
/// Server rejected the request because the Content-Length header field is not defined and the server requires it.
class LengthRequiredException extends ClientException {
LengthRequiredException(Response<dynamic> response) : super(response);
}
/// 412 Precondition Failed
///
/// The client has indicated preconditions in its headers which the server does not meet.
class PreconditionFailedException extends ClientException {
PreconditionFailedException(Response<dynamic> response) : super(response);
}
/// 413 Payload Too Large
///
/// Request entity is larger than limits defined by server. The server might close the connection or return an Retry-After header field.
class PayloadTooLargeException extends ClientException {
PayloadTooLargeException(Response<dynamic> response) : super(response);
}
/// 414 URI Too Long
///
/// The URI requested by the client is longer than the server is willing to interpret.
class UriTooLongException extends ClientException {
UriTooLongException(Response<dynamic> response) : super(response);
}
/// 415 Unsupported Media Type
///
/// The media format of the requested data is not supported by the server, so the server is rejecting the request.
class UnsupportedMediaTypeException extends ClientException {
UnsupportedMediaTypeException(Response<dynamic> response) : super(response);
}
/// 416 Range Not Satisfiable
///
/// The range specified by the Range header field in the request cannot be fulfilled. It's possible that the range is outside the size of the target URI's data.
class RangeNotSatisfiableException extends ClientException {
RangeNotSatisfiableException(Response<dynamic> response) : super(response);
}
/// 417 Expectation Failed
///
/// This response code means the expectation indicated by the Expect request header field cannot be met by the server.
class ExpectationFailedException extends ClientException {
ExpectationFailedException(Response<dynamic> response) : super(response);
}
/// 418 I'm a teapot
///
/// The HTTP 418 I'm a teapot client error response code indicates that the server refuses to brew coffee because it is, permanently, a teapot. A combined coffee/tea pot that is temporarily out of coffee should instead return 503. This error is a reference to Hyper Text Coffee Pot Control Protocol defined in April Fools' jokes in 1998 and 2014.
///
/// Some websites use this response for requests they do not wish to handle, such as automated queries.
class IamTeapotException extends ClientException {
IamTeapotException(Response<dynamic> response) : super(response);
}
/// 428 Precondition Required
///
/// The origin server requires the request to be conditional. This response is intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
class PreconditionRequiredException extends ClientException {
PreconditionRequiredException(Response<dynamic> response) : super(response);
}
/// 429 Too Many Requests
///
/// The client has sent too many requests in a given amount of time ("rate limiting").
class TooManyRequestsException extends ClientException {
TooManyRequestsException(Response<dynamic> response) : super(response);
}
/// 431 Request Header Fields Too Large
///
/// The server is unwilling to process the request because its header fields are too large. The request may be resubmitted after reducing the size of the request header fields.
class RequestHeaderFieldsTooLargeException extends ClientException {
RequestHeaderFieldsTooLargeException(Response<dynamic> response) : super(response);
}
/// 451 Unavailable For Legal Reasons
///
/// The user agent requested a resource that cannot legally be provided, such as a web page censored by a government.
class UnavailableForLegalReasonsException extends ClientException {
UnavailableForLegalReasonsException(Response<dynamic> response) : super(response);
}
/// Server error response
abstract class ServerException extends ResponseException {
ServerException(Response<dynamic> response) : super(response);
}
/// 500 Internal Server Error
///
/// The server has encountered a situation it does not know how to handle.
class InternalServerException extends ServerException {
InternalServerException(Response<dynamic> response) : super(response);
}
/// 501 Not Implemented
///
/// The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.
class NotImplementedException extends ServerException {
NotImplementedException(Response<dynamic> response) : super(response);
}
/// 502 Bad Gateway
///
/// This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
class BadGatewayException extends ServerException {
BadGatewayException(Response<dynamic> response) : super(response);
}
/// 503 Service Unavailable
///
/// The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This response should be used for temporary conditions and the Retry-After HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
class ServiceUnavailableException extends ServerException {
ServiceUnavailableException(Response<dynamic> response) : super(response);
}
/// 504 Gateway Timeout
///
/// This error response is given when the server is acting as a gateway and cannot get a response in time.
class GatewayTimeoutException extends ServerException {
GatewayTimeoutException(Response<dynamic> response) : super(response);
}
/// 505 HTTP Version Not Supported
///
/// The HTTP version used in the request is not supported by the server.
class HttpVersionNotSupportedException extends ServerException {
HttpVersionNotSupportedException(Response<dynamic> response) : super(response);
}
/// 506 Variant Also Negotiates
///
/// The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
class VariantAlsoNegotiatesException extends ServerException {
VariantAlsoNegotiatesException(Response<dynamic> response) : super(response);
}
/// 507 Insufficient Storage (WebDAV)
///
/// The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.
class InsufficientStorageException extends ServerException {
InsufficientStorageException(Response<dynamic> response) : super(response);
}
/// 508 Loop Detected (WebDAV)
///
/// The server detected an infinite loop while processing the request.
class LoopDetectedException extends ServerException {
LoopDetectedException(Response<dynamic> response) : super(response);
}
/// 510 Not Extended
///
/// Further extensions to the request are required for the server to fulfill it.
class NotExtendedException extends ServerException {
NotExtendedException(Response<dynamic> response) : super(response);
}
/// 511 Network Authentication Required.
///
/// Indicates that the client needs to authenticate to gain network access.
class NetworkAuthenticationRequiredException extends ServerException {
NetworkAuthenticationRequiredException(Response<dynamic> response) : super(response);
}
@a7md0
Copy link
Author

a7md0 commented May 2, 2022

The exceptions tree

HttpException // abstract
  NoConnectionException
  TimeoutException // abstract
    ConnectionTimeoutException
    SendTimeoutException
    ReceiveTimeoutException
  CancelException
  EmptyResponseException // Not driven from DioError; But could be thrown manually when required
  ResponseException // abstract
    ClientException // abstract 4xx
      BadRequestException
      UnauthorizedException
      ForbiddenException
      NotFoundException
      MethodNotAllowedException
      NotAcceptableException
      ProxyAuthenticationRequiredException
      RequestTimeoutException
      ConflictException
      GoneException
      LengthRequiredException
      PreconditionFailedException
      PayloadTooLargeException
      UriTooLongException
      UnsupportedMediaTypeException
      RangeNotSatisfiableException
      ExpectationFailedException
      IamTeapotException
      PreconditionRequiredException
      TooManyRequestsException
      RequestHeaderFieldsTooLargeException
      UnavailableForLegalReasonsException
    ServerException // abstract 5xx
      InternalServerException
      NotImplementedException
      BadGatewayException
      ServiceUnavailableException
      GatewayTimeoutException
      HttpVersionNotSupportedException
      VariantAlsoNegotiatesException
      InsufficientStorageException
      LoopDetectedException
      NotExtendedException
      NetworkAuthenticationRequiredException
    UndefinedResponseException // Undefined status code
  OtherException

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment