Here are the possible reasons why your MacBook keeps dying at 40-50% (and what to do about it):
Battery calibration – Your Mac’s battery calibration might be inaccurate, causing your Mac to shut down even if there’s plenty of juice left. Recalibrate your battery by following the instructions here.
Battery health – Batteries are consumable and so degrade over time. It’s possible that your Mac’s battery jumps suddenly from a decent charge (like 30% or 40%) to 0%. You may have to have it replaced by Apple.
Software issues – Faulty software or firmware can affect your battery’s behavior (as well as the components managing it). Remove suspicious apps and update macOS. If that doesn’t work, try reinstalling macOS.
Lack of power – Your Mac may not have enough power to run a certain app/s or background process/es, as well as the operating system.