.cmd and .bat file converting return code to an error message

You can do this quite neatly with the ENABLEDELAYEDEXPANSION option. This allows you to use ! as variable marker that is evaluated after %.

REM Turn on Delayed Expansion
SETLOCAL ENABLEDELAYEDEXPANSION

REM Define messages as variables with the ERRORLEVEL on the end of the name
SET MESSAGE0=Everything is fine
SET MESSAGE1=Failed for such and such a reason
SET MESSAGE2=Failed for some other reason

REM Set ERRORLEVEL - or run command here
SET ERRORLEVEL=2

REM Print the message corresponding to the ERRORLEVEL
ECHO !MESSAGE%ERRORLEVEL%!

Type HELP SETLOCAL and HELP SET at a command prompt for more information on delayed expansion.


You can do something like the following code. Note that the error level comparisons should be in decreasing order due to a cmd quirk.

setlocal

rem Main script
call :LookupErrorReason %errorlevel%
echo FAILED Test case failed, error reason: %errorreason% >> TestSuite1Log.txt
goto :EndOfScript

rem Lookup subroutine
:LookupErrorReason
  if %%1 == 3 set errorreason=Some reason
  if %%1 == 2 set errorreason=Another reason
  if %%1 == 1 set errorreason=Third reason
goto :EndOfScript

:EndOfScript
endlocal