CarpServiceRequestException.fromHttpStatus constructor

CarpServiceRequestException.fromHttpStatus(
  1. int httpStatusCode,
  2. dynamic response
)

Creates the matching exception from an HTTP httpStatusCode and the decoded JSON response body.

Returns a CarpBadRequestException, CarpUnauthorizedException, CarpNotFoundException or CarpInternalServerException for the matching status codes, and a plain CarpServiceRequestException otherwise.

There are two types of error messages - from CAWS and from NGINX. CAWS errors contain 'path' and 'exception' fields, whereas NGINX errors contain an 'instance' field.

Implementation

factory CarpServiceRequestException.fromHttpStatus(int httpStatusCode, dynamic response) {
  String? message = 'Unknown error', exception, path;

  if (response is Map<String, dynamic>) {
    if (response.containsKey('path')) {
      // CAWS error message
      message = response["message"].toString();
      exception = response["exception"].toString();
      path = response["path"].toString();
    } else if (response.containsKey('instance')) {
      // NGINX error message
      message = response["detail"].toString();
      exception = '';
      path = response["instance"].toString();
    } else {
      exception = response["exception"].toString();
      path = response["path"].toString();
    }
  }

  return switch (httpStatusCode) {
    HttpStatus.badRequest => CarpBadRequestException(message, exception: exception, path: path),
    HttpStatus.unauthorized ||
    HttpStatus.forbidden => CarpUnauthorizedException(message, exception: exception, path: path),
    HttpStatus.notFound => CarpNotFoundException(message, exception: exception, path: path),
    HttpStatus.internalServerError => CarpInternalServerException(message, exception: exception, path: path),
    _ => CarpServiceRequestException(
      message,
      httpStatus: HTTPStatus(httpStatusCode),
      exception: exception,
      path: path,
    ),
  };
}