The onerror property of the HTMLMediaElement interface specifies an event listener function which will receive error events sent to the media element. These events occur when some form of error occurs while attempting to load or perform the media.


HTMLMediaElement.onerror = EventListener;


A function which serves as the event handler for the error event. When an error occurs, the specified function will be called. If null, no error handler is in effect.


This example creates a <audio> element, establishes an error handler for it, then lets the user click buttons to choose whether to assign a valid audio file or a missing file to the element's src attribute. The error handler simply outputs a message to a box onscreen describing the error, including both the code and the message.

Only the relevant parts of the code are displayed; you can see the complete source code here.

The example creates an <audio> element and lets the user assign either a valid music file to it, or a link to a file which doesn't exist. This lets us see the behavior of the error event handler, which is received by an event handler we add to the <audio> element itself.

The error handler looks like this:

  audioElement.onerror = function() {
    let s = "";
    let err = audioElement.error;
    switch(err.code) {
      case MediaError.MEDIA_ERR_ABORTED:
        s += "The user canceled the audio.";
      case MediaError.MEDIA_ERR_NETWORK:
        s+= "A network error occurred while fetching the audio.";
      case MediaError.MEDIA_ERR_DECODE:
        s+= "An error occurred while decoding the audio.";
      case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
        s+= "The audio is missing or is in a format not supported by your browser.";
        s += "An unknown error occurred.";
    let message = err.message;
    if (message && message.length) {
      s += " " + message;
    displayErrorMessage("<strong>Error " + err.code + ":</strong> " + s + "<br>");

This gets the MediaError object describing the error from the error property on the HTMLAudioElement representing the audio player.  The error's code attribute is checked to determine a generic error message to display, and, if message is not empty, it's appended to provide additional details. Then the resulting text is output to the log.


You can try out this example below, and can see the example in action outside this page here.

Document Tags and Contributors

 Contributors to this page: Sheppy
 Last updated by: Sheppy,