How to Handle Media Errors
There is a very simple way to handle media errors in HTML5. HTML5 provides an event that fires whenever an error occurs, allowing your application to listen for it. Your application can gracefully detect and handle the event when a media player cannot play or cannot continue to play an asset:
- Error in decoding (bad codec, MOV ATOM was at end of file, etc)
- Network Error (404, etc)
- Source format not supported
The error itself is available in the event by using event.target.error which is of type MediaError. Currently there are four types of errors which are enumerated in ALL CAPS within the MediaError prototype:
The following example is a typical way to deal with an error:
The above example listens for an error, and then does a switch of the error code (1 through 4, but we do not use the numbers themselves because the constants MediaError.[[CONSTANT_NAME]] are more the standard practice and better suited for an evolving specification). We then display the appropriate friendly error message in a div with the ID errorDiv.
This is a simplistic approach. We recommend you generally provide a standard error page in your application (error.html) and pass any errors to the page (location.href = "error.html?error=Some_error_message"). That way, error messages are consistent throughout your application. However, that topic will be discussed elsewhere. Provide your users with feedback when there is an error, even when the probability of an error is near zero.