Move the defer before the error check