Q:

The syntax of the command is incorrect. at endlocal & set [batch]

I have a function which returns value by reference in batch.
:errorCheck
setlocal
set "test_command=%~1"
set "err_code=%~2"
FOR /F "delims=" %%a IN ('%test_command% 2^>^&1 1^>NUL') DO (
set err_msg="%%~a"
)
if [%err_msg%] neq [] (
    if not x%err_msg:%err_code%=%==x%err_msg% (
        set "error=true"
    )
)   

if [%err_msg%]==[] (
     set "error=false"
)
endlocal & set "%3=%error%"
exit /b

The function executes correctly and the return value is also correct but at line endlocal & set "%3=%error%" while executing set "%3=%error%" part it gives me error :
The syntax of the command is incorrect.

i am unable to comprehend why is it happening though the return value is correct.

A:

The problem is not in the return value, but in the substring operation. Your syntax is not allowed. The expression is not evaluated as you think. The start and end of variables are
%err_msg:%err_code%=%
^........^        ^.^
var1              var2

To use a variable in a substring operation in another variable you will need to use delayed expansion. Try with
:errorCheck
    setlocal enableextensions disabledelayedexpansion
    set "test_command=%~1"
    set "err_code=%~2"
    set "error=false"
    set "err_msg="

    FOR /F "delims=" %%a IN ('
        %test_command% 2^>^&1 1^>NUL
    ') DO set "err_msg=%%~a"

    if defined err_msg (
        setlocal enabledelayedexpansion
        if not "!err_msg:%err_code%=!"=="%err_msg%" (
            endlocal
            set "error=true"
        ) else ( endlocal )
    ) 

    endlocal & set "%3=%error%"
    exit /b

Now the variables seen by the parser are
!err_msg:%err_code%=!
         ^........^
^...................^

But as not all characters are allowed in a substrig operation, depending on the contents of err_code it is possible that it will also fail. 
If it can be the case, you can change the substring operation into a piped command searching for the required error code
:errorCheck testCommand errorCode returnVariable
    setlocal enableextensions disabledelayedexpansion
    ( %~1 2>&1 1>nul | find "%~2" > nul ) && ( set "error=true" ) || ( set "error=false" )
    endlocal & set "%~3=%error%"
    exit /b

That is:  

execute the command (%~1) with, as in the original code, the stdout redirected to null and stderr redirected to stdout, so we read the error stream. 
The output of the command is filtered with find, searching the error code. If it is found, find will not raise error level, if it is not found, errorlevel will be raised.
Using conditional execution, the error variable is set. If the previous command does not raise errorlevel, the code after the && is executed. If the command raised errorlevel, the code after the || is executed.
Environment space is restored and the return variable asigned

