Extract response encoding into a middleware

Invoke the stack, encode the response and store it in the env. If an
encoding error occurs, a generic Protobuf error is encoded and returned.