Matthew's gospel tells us more about Joseph.
When he found out that his betrothed, Mary, was pregnant, he knew quite well that he would not be the father of that child. Yet, he wanted to protect her to the extent possible. Rather than subject her to public disgrace, he decided to handle the situation as privately as possible.
The Lord sends him a message that changes his mind. Eugene Boring & Fred Craddock, in their People's New Testament Commentary say:
Matthew's main point is that Joseph the righteous man had already decided not to carry out the letter of the biblical and traditional law, but to act in mercy and preserve Mary's dignity with a quiet divorce. How it could be that a righteous person would not go by the written traditional law of God is a theme of Matthew's whole gospel, for the church to which he writes respects and affirms God's law, but no longer lives by it literally (see on Matt. 5:17-48).