Bash assign output/error to variable

From ssh man page on Ubuntu 16.04 (LTS):

EXIT STATUS
     ssh exits with the exit status of the remote command or with 255 if an error occurred.

Knowing that, we can check exit status of ssh command. If exit status was 225, we know that it's an ssh error, and if it's any other non-zero value - that's ls error.

#!/bin/bash

TEST=$(ssh $USER@localhost 'ls /proc' 2>&1)

if [ $? -eq 0 ];
then
    printf "%s\n" "SSH command successful"
elif [ $? -eq 225   ]
    printf "%s\n%s" "SSH failed with following error:" "$TEST"
else 
    printf "%s\n%s" "ls command failed" "$TEST"
fi

Redirect ssh's standard error to a file within the command substitution and then test to see whether the file is empty or not:

output="$( ssh server 'command' 2>ssh.err )"

if [[ -s ssh.err ]]; then
    echo 'SSH error:' >&2
    cat ssh.err >&2
fi

rm -f ssh.err

which displays SSH error: followed by the captured error output from ssh.