Stop with proper error message on api call errors

Change-Id: Ic76a7285887753cbab3929058a438150f8ec2c54
diff --git a/R/matomoquery.R b/R/matomoquery.R
index 8a8aad4..d30fc32 100644
--- a/R/matomoquery.R
+++ b/R/matomoquery.R
@@ -40,7 +40,7 @@
                              accessToken = getAccessToken(matomoUrl),
                              getMethod = "VisitsSummary.get"
 ) {
-  if (is.null(accessToken) && matomoUrl != "https://demo.matomo.org/") {
+  if ((is.null(accessToken) || accessToken == '' ) && matomoUrl != "https://demo.matomo.org/") {
     stop(
       paste0(
         "You must first set an access token with:\n\npersistAccessToken(\"",
@@ -86,15 +86,19 @@
 
   json <- httr::content(res, "text", encoding = "UTF-8")
 
+  l <- jsonlite::fromJSON(json)
+  if("result" %in% colnames(l) && l$result == 'error') {
+    stop(paste("in api call:", l$message), call. = FALSE)
+  }
+
   if (period=="range") {
     df <- if (length(siteId) == 1) {
-      jsonlite::fromJSON(json) %>%
+      l %>%
         mutate(site_id=siteId)
     } else {
       bind_rows(jsonlite::fromJSON(json), .id = "site_id")
     }
   } else {
-    l <- jsonlite::fromJSON(json)
     df <- (if (length(siteId) == 1) {
       bind_rows(l, .id=period) %>%
         head(if(removeLast) -1 else filter_limit) %>%