west build: fix board detection

We can't trust the cache to have a CACHED_BOARD just because it exists.

Fixes: #31800

Signed-off-by: Martí Bolívar <marti.bolivar@nordicsemi.no>
diff --git a/scripts/west_commands/build.py b/scripts/west_commands/build.py
index 2b2e308..9fa5f81 100644
--- a/scripts/west_commands/build.py
+++ b/scripts/west_commands/build.py
@@ -190,7 +190,13 @@
         if self.cmake_cache:
             board, origin = (self.cmake_cache.get('CACHED_BOARD'),
                              'CMakeCache.txt')
-        elif self.args.board:
+
+            # A malformed CMake cache may exist, but not have a board.
+            # This happens if there's a build error from a previous run.
+            if board is not None:
+                return (board, origin)
+
+        if self.args.board:
             board, origin = self.args.board, 'command line'
         elif 'BOARD' in os.environ:
             board, origin = os.environ['BOARD'], 'env'