We present a semidefinite program optimization approach to quantum error correction that yields codes and recovery procedures that are robust against significant variations in the noise channel. Our approach allows us to optimize the encoding, recovery, or both, and is amenable to approximations that significantly improve computational cost while retaining fidelity. We illustrate our theory numerically for optimized 5-qubit codes, using the standard [5,1,3] code as a benchmark. Our optimized encoding and recovery yields fidelities that are uniformly higher by 1-2 orders of magnitude against random unitary weight-2 errors compared to the [5,1,3] code with standard recovery. We observe similar improvement for a 4-qubit decoherence-free subspace code.