diff --git a/lib/SimpleSAML/SessionHandlerPHP.php b/lib/SimpleSAML/SessionHandlerPHP.php
index 198ea6a65b6e6a3e66738807aa7d9d55e5432857..abdb0610dd67b3400fe7236be1a986f8e6656e09 100644
--- a/lib/SimpleSAML/SessionHandlerPHP.php
+++ b/lib/SimpleSAML/SessionHandlerPHP.php
@@ -322,11 +322,17 @@ class SimpleSAML_SessionHandlerPHP extends SimpleSAML_SessionHandler
         }
 
         if ($cookieParams['secure'] && !\SimpleSAML\Utils\HTTP::isHTTPS()) {
-            throw new SimpleSAML\Error\CannotSetCookie('Secure cookies not allowed on http.');
+            throw new \SimpleSAML\Error\CannotSetCookie(
+                'Secure cookies not allowed on http.',
+                \SimpleSAML\Error\CannotSetCookie::SECURE_COOKIE
+            );
         }
 
         if (headers_sent()) {
-            throw new SimpleSAML\Error\CannotSetCookie('Headers already sent.');
+            throw new \SimpleSAML\Error\CannotSetCookie(
+                'Headers already sent.',
+                \SimpleSAML\Error\CannotSetCookie::HEADERS_SENT
+            );
         }
 
         session_set_cookie_params(
diff --git a/lib/SimpleSAML/Utils/HTTP.php b/lib/SimpleSAML/Utils/HTTP.php
index c1121de5cff8198d5ea843fec8f86b09f30380d8..a586ef8a47424d2592a202932e89037988ed57c5 100644
--- a/lib/SimpleSAML/Utils/HTTP.php
+++ b/lib/SimpleSAML/Utils/HTTP.php
@@ -1041,7 +1041,13 @@ class HTTP
 
         // Do not set secure cookie if not on HTTPS
         if ($params['secure'] && !self::isHTTPS()) {
-            Logger::warning('Setting secure cookie on plain HTTP is not allowed.');
+            if ($throw) {
+                throw new \SimpleSAML\Error\CannotSetCookie(
+                    'Setting secure cookie on plain HTTP is not allowed.',
+                    \SimpleSAML\Error\CannotSetCookie::SECURE_COOKIE
+                );
+            }
+            Logger::warning('Error setting cookie: setting secure cookie on plain HTTP is not allowed.');
             return;
         }
 
@@ -1079,10 +1085,12 @@ class HTTP
 
         if (!$success) {
             if ($throw) {
-                throw new \SimpleSAML\Error\CannotSetCookie('Headers already sent.');
-            } else {
-                Logger::warning('Error setting cookie: headers already sent.');
+                throw new \SimpleSAML\Error\CannotSetCookie(
+                    'Headers already sent.',
+                    \SimpleSAML\Error\CannotSetCookie::HEADERS_SENT
+                );
             }
+            Logger::warning('Error setting cookie: headers already sent.');
         }
     }