Remember you were not the only applicant for the job and there might be someone more deserving amongst the candidates. However, everyone has their own strengths and weaknesses. You cleared the test stage so that means you were better than almost 30% of the lot.
Console yourself and be happy for that. If you cleared the interview, the percentage can rise up to 50%. You did great anyway. Hence, there is no need to be sad.
Don’t be arrogant rather be courteous and respond the firm back for being caring enough to tell you what they though in the most desirable fashion.
You might still have a chance if you were amongst the top 5% of the candidates left in the selection process because offer to the priority candidate can be turned down by him.